Loops 如何使用R中的For循环获得矩阵中每列的最大值

Loops 如何使用R中的For循环获得矩阵中每列的最大值,loops,for-loop,matrix,max,multiple-columns,Loops,For Loop,Matrix,Max,Multiple Columns,例如:如果我有这个矩阵,并且我想使用For循环计算每个列的最大值,那么我应该做什么 X=矩阵(1:12,nrow=4,ncol=3)这可以通过使用如图所示的ncol()和max()函数来完成。一旦获得了列索引号,可以按如下方式提取相应的行: X = matrix (1:12, nrow = 4, ncol=3) #Let soln be the solution vector that stores the corresponding maximum value of each column

例如:如果我有这个矩阵,并且我想使用For循环计算每个列的最大值,那么我应该做什么


X=矩阵(1:12,nrow=4,ncol=3)

这可以通过使用如图所示的ncol()和max()函数来完成。一旦获得了列索引号,可以按如下方式提取相应的行:

X = matrix (1:12, nrow = 4, ncol=3)
#Let soln be the solution vector that stores the corresponding maximum value of each column              
soln=c()

#Traverse the matrix column-wise
for (i in 1:ncol(X))
{
  #Extract all rows of the ith column and find the maxiumum value in the same column
  soln[i]= max(X[,i])
  print(soln[i])
}

#Print the solution as a vector
soln

此外,还回答了一个类似的问题,没有使用for循环(通过使用apply()函数)。

非常感谢,Sukriti