Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the row and column name of the minimum element of a matrix

Tags:

r

matrix

I need to get the row and column name of the smallest element of a matrix

> mat = matrix(data=runif(12), nrow = 4, ncol=4) > rownames(mat) = colnames(mat) = letters[1:4] >  > mat   a         b         c         d a 0.3167865 0.6958895 0.4233572 0.3167865 b 0.1042599 0.1552235 0.8461520 0.1552235 c 0.6286461 0.9749868 0.2390978 0.6286461 d 0.5923721 0.7823673 0.8427426 0.5923721 > min = min(mat) > min > 0.1042599 

In this example I'd like to get "a" and "b"

like image 520
Sebastian Avatar asked Nov 17 '10 18:11

Sebastian


People also ask

How do you find the minimum element in a row of a matrix?

M = min( A ,[], dim ) returns the minimum element along dimension dim . For example, if A is a matrix, then min(A,[],2) is a column vector containing the minimum value of each row.

What is the command to find maximum and minimum values in a column row or matrix?

We have made use of the max() function which is used to find the maximum element present in an object. This object can be a Vector, a list, a matrix, a data frame, etc. The “which()” function is used to get the index or position of the value which satisfies the given condition.

How do you name rows and columns in a matrix?

Naming Rows and Columns of a Matrix in R Programming – rownames() and colnames() Function. rownames() function in R Language is used to set the names to rows of a matrix.

How do you find the maximum and minimum of a matrix?

Pair Comparison (Efficient method): Select two elements from the matrix one from the start of a row of the matrix another from the end of the same row of the matrix, compare them and next compare smaller of them to the minimum of the matrix and larger of them to the maximum of the matrix.


1 Answers

> inds = which(mat == min(mat), arr.ind=TRUE) > inds   row col a   1   2 > rnames = rownames(mat)[inds[,1]] > cnames = colnames(mat)[inds[,2]] 

This will give you the row/column names for each entry that equals the minimum value; if you just want the first one, you could only check inds[1,1] and inds[1,2].

like image 175
bnaul Avatar answered Oct 21 '22 14:10

bnaul