以最快的方式用数组索引按降序打印矩阵的排序元素 [英] Printing the sorted elements of a matrix in descending order with array indices in the fastest fashion
问题描述
这似乎是一个简单的问题,但我无法快速进行此操作.
This seems like a simple problem but I am having trouble doing this in a fast manner.
说我有一个矩阵,我想对该矩阵排序并按降序存储元素的索引.有没有一种快速的方法可以做到这一点?现在,我正在提取最大值,将结果存储,将其更改为-2,然后在for循环中提取下一个最大值.这可能是最无效率的方法.
Say I have a matrix and I want to sort this matrix and store the indices of the elements in descending order. Is there a quick way to do this? Right now, I am extracting the maximum, storing the result, changing it to -2, and then extracting the next maximum in a for loop. Which is probably the most inefficient way to do it.
我的问题实际上需要我处理20,000 X 20,000矩阵.内存不是问题.关于最快的方法的任何想法都将很棒.
My problem actually requires me to work on a 20,000 X 20,000 matrix. Memory is not an issue. Any ideas about the fastest way to do it 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 indicate the numbers in descending order:
row col val
2 1 4
2 2 3
1 2 2
1 1 1
推荐答案
以下是可能的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
编辑:基本R替代项
Edit: a base R alternative
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
这篇关于以最快的方式用数组索引按降序打印矩阵的排序元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!