# How to resort every column of a 3d matrix?

3 views (last 30 days)
Shayma Al Ali on 23 Aug 2023
Edited: dpb on 23 Aug 2023
I have a 3d matrix "A" with a size of 1440x720x12, which corresponds to Longitude x Latitude x Time. The longitude for this matrix has a range of -180 to 180, while other matrices I'd like to use this matrix with have longitudes with a range of 0 to 360. I'd like to convert the longitudes of matrix A so that I could easily compute each point of the matrix with the other matrices.
So far my code has been:
A.lon=wrapTo360(A.lon);
[A2,I2]=sort(A.lon);
However, I'm having trouble sorting each column of the matrix so that each point corresponds to a longitudanal range of 0 to 360?
##### 3 CommentsShow 1 older commentHide 1 older comment
Shayma Al Ali on 23 Aug 2023
I meant I have a matrix A.sst that's 1440x720x12.
And the reason why it matters is because if I want to multiple A.sst with another matrix B.u10, then it becomes an issue if B(1,1,1)'s coordinates is say (0,90) but A(1,1,1)'s coordinates is (-180,90). Then I'm not really using the same values in the same location.
Walter Roberson on 23 Aug 2023
sortrows maybe ?

dpb on 23 Aug 2023
Edited: dpb on 23 Aug 2023
L=-180:60:180
L = 1×7
-180 -120 -60 0 60 120 180
wrapTo360(L)
ans = 1×7
180 240 300 0 60 120 180
[~,ix]=sort(ans)
ix = 1×7
4 5 6 1 7 2 3
M=[1:3].*L.';
M=cat(3,M,2*M)
M =
M(:,:,1) = -180 -360 -540 -120 -240 -360 -60 -120 -180 0 0 0 60 120 180 120 240 360 180 360 540 M(:,:,2) = -360 -720 -1080 -240 -480 -720 -120 -240 -360 0 0 0 120 240 360 240 480 720 360 720 1080
M(ix,:,:)
ans =
ans(:,:,1) = 0 0 0 60 120 180 120 240 360 -180 -360 -540 180 360 540 -120 -240 -360 -60 -120 -180 ans(:,:,2) = 0 0 0 120 240 360 240 480 720 -360 -720 -1080 360 720 1080 -240 -480 -720 -120 -240 -360
sortrows doesn't operate on 3D arrays so would have to use it by plane in loop or arrayfun() construct; indexing works by dimension so getting the sorted order along the first dimension lets you rearrange all planes in that order in one step.
The description of the input as going from -180:180 leaves with a possible problem that the wrapTo360 and sort moves the first element to be ahead of the last in the sorted order; they are redundant as are 0 and 360 in the alternate universe so whether this is actually so or only approximately so that one bound ends just before the boundary value we don't know.
If is duplicated, then one could choose to swap the middle indices before rearranging.
Or
circshift(M,-fix(size(M,1)/2),1)
ans =
ans(:,:,1) = 0 0 0 60 120 180 120 240 360 180 360 540 -180 -360 -540 -120 -240 -360 -60 -120 -180 ans(:,:,2) = 0 0 0 120 240 360 240 480 720 360 720 1080 -360 -720 -1080 -240 -480 -720 -120 -240 -360