Reputation: 43
I am trying to sort first row in the 2nd dimension of a 3d matrix in Matlab, but sortrows() doesn't work in this case.
For example, I have a matrix like
a(:,:,1)
1 2 4
3 1 6
2 0 5
a(:,:,2)
3 5 6
1 2 4
0 2 2
and I need to get the result
a(:,:,1)
1 2 4
2 0 5
3 1 6
a(:,:,2)
0 2 2
1 2 4
3 5 6
Is there an efficient way to achieve that? Thanks a lot!
Upvotes: 4
Views: 537
Reputation: 112659
If I understand correctly, you want to sort rows within each third-dim slice according to the value of the first column.
[m,n,p] = size(a);
[~, row_ind] = sort(a(:,1,:), 1);
lin_ind = bsxfun(@plus, bsxfun(@plus, row_ind, (0:n-1)*m), reshape((0:p-1)*m*n, 1, 1, p));
result = a(lin_ind);
How this works:
Sort a(:,1:,)
along the first dimension (rows), and get the indices of the sorting (using the second output of sort
; line 2). From those row indices, generate the linear indices (using bsxfun
; line 3) that will give the desired result (line 4).
Example:
For input
a(:,:,1) = [1 2 4
3 1 6
2 0 5];
a(:,:,2) = [3 5 6
1 2 4
0 2 2];
this produces
result(:,:,1) =
1 2 4
2 0 5
3 1 6
result(:,:,2) =
0 2 2
1 2 4
3 5 6
Upvotes: 4
Reputation: 4408
Just use sortrows
with each 2d matrix:
a(:,:,1)=sortrows(a(:,:,1));
a(:,:,2)=sortrows(a(:,:,2));
Of course you can do it in a loop
Upvotes: 2