Printing sorted matrix elements in descending order with array indices in fastest way

This seems like a simple problem, but I'm having problems with it quickly.

Let's say I have a matrix and I want to sort this matrix and keep the element indices in descending order. Is there a quick way to do this? Right now, I'm fetching the maximum, storing the result, changing it to -2, and then fetching the next maximum in a for loop. This is most likely the most inefficient way to do it.

My problem actually requires me to work with a 20,000 x 20,000 matrix. Memory is not an issue. Any ideas on the fastest way to do this would be great.

For example, if I have a matrix

>m<-matrix(c(1,4,2,3),2,2)
>m
     [,1] [,2]
[1,]    1    2
[2,]    4    3

      

I want the result to list the numbers in descending order:

 row  col val
 2    1   4
 2    2   3
 1    2   2
 1    1   1

      

+3


source to share


1 answer


Here's a possible solution data.table

library(data.table)
rows <- nrow(m) ; cols <- ncol(m)
res <- data.table(
                  row = rep(seq_len(rows), cols), 
                  col = rep(seq_len(cols), each = rows),
                  val = c(m)
)
setorder(res, -val)
res
#    row col val
# 1:   2   1   4
# 2:   2   2   3
# 3:   1   2   2
# 4:   1   1   1

      




Edit : basic alternative to R

res <- cbind(
        row = rep(seq_len(rows), cols), 
        col = rep(seq_len(cols), each = rows),
        val = c(m)
)    
res[order(-res[, 3]),]
#      row col val
# [1,]   2   1   4
# [2,]   2   2   3
# [3,]   1   2   2
# [4,]   1   1   1

      

+4


source







All Articles