0
votes

For Example: If I have this matrix and I want to calculate the maximum value of each column using the for loop what I should do

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

1

1 Answers

0
votes

This can be done by using the ncol() and max() functions as shown.Once the column index numbers are obtained, the corresponding rows can be extracted as follows:

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

Also,a similar question was answered here,without the usage of a for loop (by using the apply() function).