Rank value matrix from 3d Matrix
이전 댓글 표시
I have a 3d matrix of average global temperatures (0.5 degree lat/long) for 42 years (42×720×1440). For a given year (say year 42) I want to create a new matrix (720 × 1440) that ranks each lat/long pair based on the other 41 years. So if a lat/long pair is warmest, it will have a rank value of 1. If it's coolest, it will have a rank value of 42. The resulting matrix will be 720 x 1440 matrix of values ranked from 1 to 42 based on the original matrix. Is there a simple way to take a given year from the original matrix to do this without looping?
채택된 답변
추가 답변 (1개)
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
John Cruce
2024년 5월 8일
Am I missing something or is the solution I'm seeking unclear?
No way to know, since you haven't demonstrated the defect you see in the results. But given that James and I reached the same solution for you, and given that you haven't cited a problem with the results in James' example, it is likely you are mis-evaluating the results on your own data.
John Cruce
2024년 5월 8일
편집: John Cruce
2024년 5월 8일
James Tursa
2024년 5월 8일
@John Cruce You're right, this needs another step. See my edit above.
Steven Lord
2024년 5월 8일
Can you construct a smaller 3-D array for which the solutions @Matt J and @James Tursa provided don't give the answer you expected/wanted and show the answer you did expect? As an example, give us a 3-by-4-by-5 array (something small enough to easily include in a comment) and the 4-by-5 matrix that is the right answer for that array? That concrete example may help us better understand how the provided solutions fail to satisfy your needs.
카테고리
도움말 센터 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!