Inverse of sorting arrangement
45 ビュー (過去 30 日間)
古いコメントを表示
[B,I] = sort(A) output is such that B = A(I). What would be the most efficient way to rather get B and J, such that A = B(J)?
0 件のコメント
採用された回答
Stephen23
2018 年 10 月 4 日
編集済み: Stephen23
2023 年 6 月 27 日
Assuming that A is a vector:
[B,I] = sort(A);
[~,J] = sort(I);
B(J)
If you have a matrix/array, then you first need to define what the intended effect is: to sort elements along one dimension (e.g. separately sort each column or row of a matrix) or to sort the rows atomically (i.e. using SORTROWS).
4 件のコメント
Mohamed Eldin
2023 年 6 月 27 日
I used the command "sortrows" and it worked perfectly
as in the following example:
[Indata,id] = sortrows(InData,1); % sort InData
[~,ids] = sortrows(id,1); % sort the index
InData_returne = Indata(ids,:); % return InData again
Stephen23
2023 年 6 月 27 日
@Mohamed Eldin: you do not need the 2nd SORTROWS, a simple SORT is quite sufficient:
[B,I] = sortrows(A,1);
[~,J] = sort(I);
A = B(J,:);
Also note that if you are only sorting one column instead of SORTROWS you could use indexing & SORT:
[B,I] = sort(A(:,1));
その他の回答 (2 件)
Matt J
2018 年 10 月 4 日
編集済み: Matt J
2018 年 10 月 4 日
[B,I] = sort(A);
J=1:numel(I);
J(I)=J;
Bruno Luong
2023 年 6 月 27 日
If A has distinct elements such as
A = rand(1,10)
a single line command is
[B,~,J] = unique(A);
Check
J
B(J)
1 件のコメント
Bruno Luong
2023 年 6 月 27 日
If A has non distinct element, then the above method gives B that is shorter than A (and B has distinct elements) and
B(J) = A
still hold.
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!