# Rank value matrix from 3d Matrix

3 views (last 30 days)

Show older comments

##### 0 Comments

### Accepted Answer

Matt J
on 8 May 2024

Edited: Matt J
on 8 May 2024

Also how can NaN values be ignored in this solution?

Here's a revised method (loop-free) that also handles NaNs. As before, ranks(:,:,i) represents the rankings for year i.

T = randi(100,3,2,5); T(1)=nan; % random temp data (with NaN)

P=permute(T,[2,3,1])

nanmap=isnan(P);

P(nanmap)=-inf;

[~,ranks]=sort(P ,3,'descend');

[~,ranks]=sort(ranks,3);

ranks(nanmap)=nan

##### 1 Comment

Matt J
on 8 May 2024

Edited: Matt J
on 8 May 2024

Here's a potentially more optimized implementation which requires only 1 sorting op, which is to be done with the attached file sortlidx.

T = randi(100,3,2,5); T(1)=nan; % random temp data (with NaN)

P=permute(T,[2,3,1])

nanmap=isnan(P);

P(nanmap)=-inf;

[~,I]=sortlidx(P ,3,'descend');

ranks=reshape(1:numel(I), size(P));

ranks(I)=ranks;

[~,~,ranks]=ind2sub(size(P), ranks);

ranks(nanmap)=nan

### More Answers (1)

James Tursa
on 8 May 2024

Edited: James Tursa
on 8 May 2024

Might be easier to permute first so that your 2D matrices are in the first two spots. Then simply use sort() to get the rank indexing you want. E.g.,

T = randi(100,3,3,4) % random temp data

P = permute(T,[2,3,1]) % permute the data so grid is first two dimensions

[~,R] = sort(P,3,'descend') % generate the ranks based on 3rd dimension

R(:,:,1) % pick off 1st year ranks

R(:,:,2) % pick off 2nd year ranks

etc.

*** EDIT ***

Needs another step to get the rankings:

n = size(R,1) * size(R,2);

M = reshape(1:n,size(R,1),size(R,2));

K = zeros(size(R));

for k=1:size(R,3)

X = M + n * (R(:,:,k)-1);

K(X(:)) = k;

end

K

Probably a way to do this without looping but I don't see it at the moment. I just saw your NaN comment. What specifically do you want to happen with NaN values? Get lowest ranking, or ...? E.g., to force them to get lowest ranking you could just do this with the sort

[~,R] = sort(P,3,'descend','MissingPlacement','last');

##### 5 Comments

Steven Lord
on 8 May 2024

### See Also

### Community Treasure Hunt

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

Start Hunting!