how to reverse a matrix (nxm) sorting?

5 vues (au cours des 30 derniers jours)
Amine Alrharad
Amine Alrharad le 13 Mar 2023
Commenté : Amine Alrharad le 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);

Réponse acceptée

Stephen23
Stephen23 le 13 Mar 2023
Modifié(e) : Stephen23 le 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 commentaires
Amine Alrharad
Amine Alrharad le 13 Mar 2023
Amazing Stephen23! it worked perfectly, thank you a lot.
Amine Alrharad
Amine Alrharad le 13 Mar 2023
Sorry that I accepted late!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by