Star
Star

Reputation: 2299

Sort elements in each row of a 3-d matrix in Matlab

I want to sort the elements in each row of a 3-d matrix A in Matlab. This matrix has dimension (m)x(n)x(g). g is set equal to 3. The order should be done in ascending order, firstly wrto A(:,:,1), then A(:,:,2) and finally A(:,:,3).

For example:

A(:,:,1)=[3 1 1; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 3 4; 1 4 0; 0 1 0; 2 1 7];
A(:,:,3)=[6 7 9; 6 6 0; 6 5 0; 0 0 0];

%Step 1: Order wrto A(:,:,1)
A(:,:,1)=[1 1 3; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 4 3; 1 4 0; 0 1 0; 2 1 7];
A(:,:,3)=[7 9 6; 6 6 0; 6 5 0; 0 0 0];

%Step 2: Within the order in Step 1, order wrto A(:,:,2)
A(:,:,1)=[1 1 3; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 4 3; 1 4 0; 0 0 1; 1 2 7];
A(:,:,3)=[7 9 6; 6 6 0; 6 0 5; 0 0 0];

%Step 3: Within the order in Step 1 and 2, order wrto A(:,:,3)
A(:,:,1)=[1 1 3; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 4 3; 1 4 0; 0 0 1; 1 2 7];
A(:,:,3)=[7 9 6; 6 6 0; 0 6 5; 0 0 0];

Upvotes: 0

Views: 56

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You can apply sortrows to each horizontal slice of A, seen from above (so that the third dimension becomes the "rows" in "sortrows"):

B = NaN(size(A));
for n = 1:size(A,1),
    B(n,:,:) = sortrows(squeeze(A(n,:,:)));
end

Upvotes: 3

Related Questions