How do I sort the second layer of a 3D matrix based on the first layer?

I have a big matrix of values, and I need to sort the rows to run from smallest to largest. This would be easy, if it weren't for the fact that each value in the row is paired with a corresponding decimal value the second layer, and I can't lose the pairing.
Example: Say I need to sort this 3x2x2 array:
First layer
1 2
5 4
0 -1
Second Layer
0.5 0.3
0.7 0.2
0 0.8
Running "sort" on it would simply order the rows in both layers, whereas I would need to maintain the pairings (1 with 0.5, 2 with 0.3), etc:
First Layer
1 2
4 5
-1 0
Second Layer
0.5 0.3
0.2 0.7
0.8 0
Can anyone suggest an efficient way for me to do this?

1 Comment

For anyone reading this, messing around with it, this also works. Data is the original array, sorted is the sorted first layer of data, and newRates is the sorted second layer of data that we're creating.
[sorted, index] = sort(data, 2);
newRates = zeros(size(sorted,1), size(sorted,2));
for ii = 1:(size(data,1))
for jj = 1:(size(data,2))
newRates(ii,jj) = data(ii, index(ii, jj), 2);
end
end
sorted(:,:,2) = newRates;

Sign in to comment.

 Accepted Answer

I'm fairly sure there's always a better way of doing things than what I do, but here is what I came up with quickly.
A = data(:,:,1);
[B, I] = sort(A,1); % Sort by rows ascending order
for k = 2:size(data,3);
for j = 1:size(data,2);
for i = 1:size(data,1);
sorted(I(i,j),j,k) = data(i,j,k);
end
end
end

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!