Rearrange elements of matrix based on an index matrix

3 views (last 30 days)
I have a 5x3 matrix and I want to rearrange each row according to the correponding row of a 5x3 index matrix
x=randn(5,3)
x = 5x3
-0.2616 0.3522 -0.4451 -1.1699 0.8921 1.7676 1.4354 1.1977 -0.3197 -1.2002 0.9392 0.7452 -0.8374 -1.3827 0.2679
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
z=randn(5,3)
z = 5x3
-0.1687 0.4662 1.3644 0.1290 -3.2728 -0.8944 -0.7820 0.2506 -1.0295 0.0976 -0.0797 -0.2671 0.2607 -0.0966 -0.1679
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[~,I]=sort(x,2)
I = 5x3
3 1 2 1 2 3 3 2 1 1 3 2 2 1 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Now I want to sort rows of z using the index matrix I. But using the following does not work. For example, I want the first row of zz to be sorted according to the first row of x, which should result in zz(1,:)= [1.3644, -0.1687, 0.4662].
zz=z(I)
zz = 5x3
-0.7820 -0.1687 0.1290 -0.1687 0.1290 -0.7820 -0.7820 0.1290 -0.1687 -0.1687 -0.7820 0.1290 0.1290 -0.1687 -0.7820
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Accepted Answer

Stephen23
Stephen23 on 27 Aug 2024
Edited: Stephen23 on 27 Aug 2024
Yes, it is awkward.
x=randn(5,3)
x = 5x3
0.9687 -0.7929 2.0516 -0.1236 0.2917 -0.9487 -1.4717 0.0275 1.1722 0.2800 1.5357 0.2596 -0.9693 -0.1854 0.3145
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
z=randn(5,3)
z = 5x3
-1.6696 0.6182 -1.4586 0.1528 1.6729 1.4683 0.3576 -1.0089 0.8616 2.1993 0.6213 -1.2327 -0.3246 -0.8133 1.0463
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[~,I] = sort(x,2)
I = 5x3
2 1 3 3 1 2 1 2 3 3 1 2 1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Perhaps
S = size(I);
[R,~] = ndgrid(1:S(1),1:S(2));
J = sub2ind(S,R,I);
zz = z(J)
zz = 5x3
0.6182 -1.6696 -1.4586 1.4683 0.1528 1.6729 0.3576 -1.0089 0.8616 -1.2327 2.1993 0.6213 -0.3246 -0.8133 1.0463
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or
zz = z;
for k = 1:size(I,1)
zz(k,:) = zz(k,I(k,:));
end
zz
zz = 5x3
0.6182 -1.6696 -1.4586 1.4683 0.1528 1.6729 0.3576 -1.0089 0.8616 -1.2327 2.1993 0.6213 -0.3246 -0.8133 1.0463
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or
zz = cell2mat(cellfun(@(v,x)v(x),num2cell(z,2),num2cell(I,2),'uni',0))
zz = 5x3
0.6182 -1.6696 -1.4586 1.4683 0.1528 1.6729 0.3576 -1.0089 0.8616 -1.2327 2.1993 0.6213 -0.3246 -0.8133 1.0463
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!