Reputation: 333
I am having trouble sorting a 3D matrix by whichever row I want, but still having the other two columns match up with the one sorted row.
ex)before sort:
5 4 1
4 6 3
9 6 5
after sort:
1 4 5
3 6 4
5 6 9
So only the first row got sorted in ascending order, the other two rows simply stayed in their respective columns.
I have tried sort(Matrix(1,:,:)), but this seems to sort all three rows.I'm guessing there is some matlab function that can do this, but I haven't found anything. Thanks
Upvotes: 0
Views: 500
Reputation: 3898
Another approach using sortrows
%// Input
a = [5 4 1
4 6 3
9 6 5]
%// code
sortrows(A.').' %// for 2D
%// Results:
1 4 5
3 6 4
5 6 9
------------------------------------------------
[t,ind] = sortrows(A(:,:,1).') %// for 3D
A(:,ind,:)
Upvotes: 1
Reputation: 13945
You can use output arguments with sort
to reorder the matrix as you want with indexing.
Example:
clear
clc
a = [5 4 1
4 6 3
9 6 5]
%// Select row of interest
row = 1;
[values,indices] = sort(a(row,:)) %// Since you have a 3D matrix use "a(row,:,:)"
b = a(:,indices) %// In 3D use "b = a(:,indices,:)"
Output:
b =
1 4 5
3 6 4
5 6 9
Upvotes: 2