如何使用 R 中的 For 循环获取矩阵中每一列的最大值
How can I get a max value of each column in matrix using For Loop in R
例如:如果我有这个矩阵,我想使用 for 循环计算每列的最大值,我应该怎么做
X = 矩阵 (1:12, nrow = 4, ncol=3)
这可以通过使用ncol()和max()函数来完成,因为shown.Once获得了列索引号,相应的行可以提取如下:
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() 函数)的情况下回答了类似的问题 here。
例如:如果我有这个矩阵,我想使用 for 循环计算每列的最大值,我应该怎么做
X = 矩阵 (1:12, nrow = 4, ncol=3)
这可以通过使用ncol()和max()函数来完成,因为shown.Once获得了列索引号,相应的行可以提取如下:
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() 函数)的情况下回答了类似的问题 here。