Is there faster ranking for matrices than double sort()?

조회 수: 1 (최근 30일)
Marin Genov
Marin Genov 2022년 9월 16일
편집: Marin Genov 2022년 9월 16일
I have a uint16 matrix, where I want to determine the rank of each element with respect to its column in sorted form. The sort function doesn't quite do this, but using the second output twice does it. I need to repeat this routine many times in my code, and profiling reveals that it's by far the slowest part. So, I was wondering if there is a faster way to accomplish this (double sort() seems a bit of an overkill for this perhaps).
Here is a MWE:
M = 50;
m = 50;
n = 2000;
A = randi(M,m,n,'uint16'); % generate an example matrix
% Ranking via double sort():
tic;
[~,I] = sort(A,1);
[~,R] = sort(I,1);
toc;

채택된 답변

Bruno Luong
Bruno Luong 2022년 9월 16일
편집: Bruno Luong 2022년 9월 16일
Not sure it is faster, but on the theorical complexity it is better (single sort).
A = randi(10,5,3)
A = 5×3
10 5 9 9 1 5 9 3 9 8 3 3 1 9 2
[~,I] = sort(A,1);
[m,n] = size(A);
R = zeros(m,n);
R(I+(0:n-1)*m) = repmat((1:m)',1,n)
R = 5×3
5 4 4 3 1 3 4 2 5 2 3 2 1 5 1
  댓글 수: 9
Bruno Luong
Bruno Luong 2022년 9월 16일
Are you sure? it looks fine to me for toy example
A = randi(10,5,3);
[~,I] = sort(A,1);
[m,n] = size(A);
% double sort
[~,R] = sort(I,1)
R = 5×3
1 4 5 3 1 1 4 3 2 5 2 3 2 5 4
% accumarray
R=accumarray(reshape(I+(0:n-1)*m,[],1),repmat((1:m)',n,1),[m*n,1]); % EDIT BUG FIX
R=reshape(R,m,n)
R = 5×3
1 4 5 3 1 1 4 3 2 5 2 3 2 5 4
Marin Genov
Marin Genov 2022년 9월 16일
편집: Marin Genov 2022년 9월 16일
@Bruno Luong: Apologies, I forgot to rename the R from the new method after copying the code, so MATLAB compared the original output again with the old output that was still in the workspace. Everything seems fine now. Many thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by