how to reverse a matrix (nxm) sorting?

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);

 採用された回答

Stephen23
Stephen23 2023 年 3 月 13 日
編集済み: Stephen23 2023 年 3 月 13 日

1 投票

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 件のコメント

Amine Alrharad
Amine Alrharad 2023 年 3 月 13 日
Amazing Stephen23! it worked perfectly, thank you a lot.
Amine Alrharad
Amine Alrharad 2023 年 3 月 13 日
Sorry that I accepted late!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by