R18
R18

Reputation: 1560

Matrix indices ordered by the value they contain

I have a matrix like this:

 mat<-matrix(c(10,45,2,15,3,98,1,7,13),nrow = 3)

mat
     [,1] [,2] [,3]
[1,]   10   15    1
[2,]   45    3    7
[3,]    2   98   13

I want to get the indices of ordered values, as what we can get from order(x, arr.idx = T) but applied to a matrix. That is:

   [,1]  [,2]
     1    3
     3    1
     2    2
     2    3
     1    1
     3    3
     1    2
     2    1
     3    2

Is it there a fast way to do it?

Thank you in advance

Upvotes: 2

Views: 39

Answers (2)

lukeA
lukeA

Reputation: 54237

You can use

arrayInd(order(mat), dim(mat), dimnames(mat))
#      [,1] [,2]
# [1,]    1    3
# [2,]    3    1
# [3,]    2    2
# [4,]    2    3
# [5,]    1    1
# [6,]    3    3
# [7,]    1    2
# [8,]    2    1
# [9,]    3    2

Upvotes: 5

akrun
akrun

Reputation: 887048

Using the order as index, we rearrange the row and col of 'mat' and cbind it to get the row/column index of the ordered values

i1 <- order(mat)
cbind(row(mat)[i1], col(mat)[i1])
#      [,1] [,2]
#[1,]    1    3
#[2,]    3    1
#[3,]    2    2
#[4,]    2    3
#[5,]    1    1
#[6,]    3    3
#[7,]    1    2
#[8,]    2    1
#[9,]    3    2

Upvotes: 3

Related Questions