【发布时间】:2017-07-24 08:26:46
【问题描述】:
例如:如果我有这个矩阵并且我想使用 for 循环计算每列的最大值我应该怎么做
X = 矩阵 (1:12, nrow = 4, ncol=3)
【问题讨论】:
标签: loops for-loop matrix max multiple-columns
例如:如果我有这个矩阵并且我想使用 for 循环计算每列的最大值我应该怎么做
X = 矩阵 (1:12, nrow = 4, ncol=3)
【问题讨论】:
标签: loops for-loop matrix max multiple-columns
这可以通过使用如图所示的 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
此外,here 也回答了一个类似的问题,但没有使用 for 循环(通过使用 apply() 函数)。
【讨论】: