w3resource

R Programming: Find row and column index of maximum and minimum value in a given matrix

R Programming: Matrix Exercise-11 with Solution

Write a R program to find row and column index of maximum and minimum value in a given matrix.

Sample Solution:

R Programming Code:

m = matrix(c(1:16), nrow = 4, byrow = TRUE)
print("Original Matrix:")
print(m)
result = which(m == max(m), arr.ind=TRUE)
print("Row and column of maximum value of the said matrix:")
print(result)
result = which(m == min(m), arr.ind=TRUE)
print("Row and column of minimum value of the said matrix:")
print(result)

Sample Output:

[1] "Original Matrix:"
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16
[1] "Row and column of maximum value of the said matrix:"
     row col
[1,]   4   4
[1] "Row and column of minimum value of the said matrix:"
     row col
[1,]   1   1                

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to convert a given matrix to a list of column-vectors.
Next: Write a R program to rotate a given matrix 90 degree clockwise rotation.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.