How to sort rows of a 2D array based on another array

8 ビュー (過去 30 日間)
Vojtech Vanecek
Vojtech Vanecek 2023 年 2 月 3 日
コメント済み: Vojtech Vanecek 2023 年 2 月 6 日
Hi,
I would like to ask how can I sort rows of one 2D array based on values in another 2D array with same dimensions without using loop. For example: Sort rows of B based on rows of A
A = [1 2 3;2 1 3;3 2 1]
B = [0 1 2;0 1 2;0 1 2]
the result is newB = [0 1 2;1 0 2;2 1 0]
My gimmicky solution using loop is:
[~,idx] = sort(A,2)
for i=1:height(B)
B(i,:) = B(i,idx(i,:))
end
Is there cleaner slution?
Thanks.
Vojta

採用された回答

DGM
DGM 2023 年 2 月 3 日
Here's one example. I'm sure there are others.
A = [1 2 3;2 1 3;3 2 1];
B = [0 1 2;0 1 2;0 1 2];
% get sorting and size info
sz = size(B);
[~,cidx] = sort(A,2);
% sort in a loop
C = zeros(sz);
for r = 1:sz(1)
C(r,:) = B(r,cidx(r,:));
end
C
C = 3×3
0 1 2 1 0 2 2 1 0
% use sub2ind()
ridx = repmat((1:sz(1)).',[1 sz(2)]);
idx = sub2ind(sz(1:2),ridx,cidx);
D = B(idx)
D = 3×3
0 1 2 1 0 2 2 1 0
  1 件のコメント
Vojtech Vanecek
Vojtech Vanecek 2023 年 2 月 6 日
Thanks a lot. I did not know about the sub2ind function.

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

その他の回答 (1 件)

Vilém Frynta
Vilém Frynta 2023 年 2 月 3 日
編集済み: Vilém Frynta 2023 年 2 月 3 日
Zdravím kolego, // Hello,
I have tried something. I can't say it's "cleaner solution", but it's without for loop. You basically unfold matrix into one vector, and then you do not need a loop.
% original variables
A = [1 2 3;2 1 3;3 2 1];
B = [0 1 2;0 1 2;0 1 2];
% modified variables -- make them into a vector
newB = B';
newB = newB(1:numel(B));
newIdx = A';
newIdx = newIdx(1:numel(B));
final_B = newB(newIdx);
final_B = reshape(final_B,[3 3])'
final_B = 3×3
0 1 2 1 0 2 2 1 0
  1 件のコメント
Vojtech Vanecek
Vojtech Vanecek 2023 年 2 月 6 日
Dobrý den/Hi,
thanks for the idea. Unfolding the matrix into a vector makes it easier.

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by