Reordering strings of multiple arrays in Matlab
Consider three of the matrix X1
, X2
, X3
in Matlab dimension Nx(N-1)
, which lists some of the integers among 0,1,...,10
.
I want to change the order of elements in each row X1
, X2
, X3
wrto X1
, and then X2
(if some elements X1
are equal) , and then X3
( if some items of X2
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 please suggest more efficient alternatives (if any) for when size(Y,1)
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);
source to share
Since the numbers are between 0
and 10
, you can easily combine the three matrices into one for sorting purposes (step 1); sort each row of the combined matrix and get the indices of this sort (step 2); and from this build a linear index (step 3) that you can use in the original matrices (step 4):
M = 11; % Strict upper bound on possible values Y = X1 + X2/M + X3/M^2; % STEP 1: combined matrix [~, cols] = sort(Y, 2); % STEP 2: sort each row and get indices of sorting ind = bsxfun(@plus, (1:size(X1,1)).', (cols-1)*size(X1,1)); % STEP 3: linear index X1new = X1(ind); % STEP 4: result X2new = X2(ind); X3new = X3(ind);
source to share
This can be done simply by using the 'sort' command in Matlab
X1new = sort(X1,2);
X2new = sort(X2,2);
X3new = sort(X3,2);
source to share