Reordering rows of several arrays in Matlab

Viewed 82

Consider three matrices X1, X2, X3 in Matlab of dimension Nx(N-1) listing some integers among 0,1,...,10.

I want to reorder the elements in each row of X1, X2, X3 wrto X1, then X2 (if some elements of X1 are equal), then X3 (if some elements of X2 are equal) in ascending order.

Example 1

N=3;
X1=[3 8;
    7 7;
    2 1];

X2=[10 1;
    10 9;
    4 4];


X3=[1 1;
    1 0;
    1 0];

%I want to obtain
X1new=[3 8;
       7 7;
       1 2];

X2new=[10 1;
       9 10;
       4 4];

X3new=[1 1;
       0 1;
       0 1];

Example 2

N=4;
X1=[3 8 9;
    7 6 6;
    2 1 4;
    4 4 4];

X2=[10 1 2;
    9  10 10;
    4 4 5;
    5 5 2];


X3=[1 1 1;
    0 0 1;
    1 0 0;
    0 0 0];


%I want to obtain
X1new=[3 8 9;
       6 6 7;
       1 2 4;
       4 4 4];

X2new=[10 1 2;
       10 10 9;
       4 4 5;
       2 5 5];

X3new=[1 1 1;
       0 1 0;
       0 1 0;
       0 0 0];

This code does what I want. Could you suggest more efficient alternatives (if any) for cases in which size(Y,1) is large?

% 1) Create a 3d matrix Y of dimension Nx(N-1)x3
Y=NaN(N,N-1,3);
Y(:,:,1)=X1;
Y(:,:,2)=X2;
Y(:,:,3)=X3;

% 2) Reorder elements in each row (independently) 
     %wrto Y(:,:,1), then Y(:,:,2), then Y(:,:,3) in ascending order.
     %Store everything in Ynew of dimension Nx(N-1)x3 
Ynew = NaN(N,N-1,3);
for h = 1:size(Y,1),
    Ynew (h,:,:) = sortrows(squeeze(Y(h,:,:)), [1 2 3]);
end

% 3) Create X1new, X2new, X3new
X1new=Ynew(:,:,1);
X2new=Ynew(:,:,2);
X3new=Ynew(:,:,3);
3 Answers
Related