2017-03-04 174 views
0

例如使用for循环矩阵中的每一列的最大值:如果我有这个矩阵,我想用for循环,我应该做些什么来计算每列的最大值我怎样才能获得R中

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

回答

0

这可以通过使用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()函数)。

+0

非常感谢你,Sukriti – Elwakdy