how to reverse a matrix (nxm) sorting?

8 views (last 30 days)
Hello everyone,
I have a matrix of order n by m, I did the sorting using the function sort of matlab. My question is how to undo the sorting using the indices matrix. Thank you.
[xs, indices] = sort(x,2);

Accepted Answer

Stephen23
Stephen23 on 13 Mar 2023
Edited: Stephen23 on 13 Mar 2023
x = rand(3,5)
x = 3×5
0.6428 0.5405 0.0059 0.3771 0.6076 0.2188 0.6466 0.3516 0.8349 0.1247 0.7154 0.2137 0.6896 0.0731 0.6152
[xs, is] = sort(x,2)
xs = 3×5
0.0059 0.3771 0.5405 0.6076 0.6428 0.1247 0.2188 0.3516 0.6466 0.8349 0.0731 0.2137 0.6152 0.6896 0.7154
is = 3×5
3 4 2 5 1 5 1 3 2 4 4 2 5 3 1
Method one: NDGRID and SUB2IND:
sz = size(x);
[~,ic] = sort(is,2);
[ir,~] = ndgrid(1:sz(1),1:sz(2));
ix = sub2ind(size(x),ir,ic);
y = xs(ix)
y = 3×5
0.6428 0.5405 0.0059 0.3771 0.6076 0.2188 0.6466 0.3516 0.8349 0.1247 0.7154 0.2137 0.6896 0.0731 0.6152
isequal(x,y)
ans = logical
1
Method two: FOR loop:
y = nan(size(x));
for k = 1:size(x,1)
y(k,is(k,:)) = xs(k,:);
end
display(y)
y = 3×5
0.6428 0.5405 0.0059 0.3771 0.6076 0.2188 0.6466 0.3516 0.8349 0.1247 0.7154 0.2137 0.6896 0.0731 0.6152
isequal(x,y)
ans = logical
1
  2 Comments
Amine Alrharad
Amine Alrharad on 13 Mar 2023
Amazing Stephen23! it worked perfectly, thank you a lot.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!