how to reverse a matrix (nxm) sorting?
8 views (last 30 days)
Show older comments
Amine Alrharad
on 13 Mar 2023
Commented: Amine Alrharad
on 13 Mar 2023
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);
0 Comments
Accepted Answer
Stephen23
on 13 Mar 2023
Edited: Stephen23
on 13 Mar 2023
x = rand(3,5)
[xs, is] = sort(x,2)
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)
isequal(x,y)
Method two: FOR loop:
y = nan(size(x));
for k = 1:size(x,1)
y(k,is(k,:)) = xs(k,:);
end
display(y)
isequal(x,y)
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting 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!