フィルターのクリア

Order columns of matrix based on other matrix

2 ビュー (過去 30 日間)
link
link 2021 年 1 月 28 日
コメント済み: link 2021 年 1 月 28 日
So in one matrix A I have the order of the elements
A = 3 1 3 1 3
2 2 2 2 1
1 3 1 3 2
and in the other matrix B are the actual values
B = 1 5 5 1 7
2 6 7 2 4
4 8 8 6 5
How can I use the columns of A to order the columns of B?
Result = 4 5 8 1 5
2 6 7 2 7
1 8 5 6 4
So e.g. for the 5th column: 5 becomes the first value, 7 the first and 4 the third.
result(1,5) = B(A(1,5), 5); % A(1,5) = 3
result(2,5) = B(A(2,5), 5); % A(2,5) = 1
result(3,5) = B(A(3,5), 5); % A(3,5) = 2
Can I do this without using a loop?

採用された回答

David Hill
David Hill 2021 年 1 月 28 日
Result=B(A+[0:3:12]);
  2 件のコメント
Adam Danz
Adam Danz 2021 年 1 月 28 日
Nice idea. To make it work for all matrix sizes,
Result=B(A+[0:size(A,1):numel(A(:,1:end-1))]);
link
link 2021 年 1 月 28 日
Thanks :) very neat

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

その他の回答 (1 件)

Adam Danz
Adam Danz 2021 年 1 月 28 日
Secret ingredient: sub2ind
A = [3 1 3 1 3
2 2 2 2 1
1 3 1 3 2 ];
B = [1 5 5 1 7
2 6 7 2 4
4 8 8 6 5 ];
cols = (1:size(A,2)).*ones(size(A,1),1);
ind = sub2ind(size(B),A,cols);
Result = B(ind)
Result = 3×5
4 5 8 1 5 2 6 7 2 7 1 8 5 6 4
  1 件のコメント
link
link 2021 年 1 月 28 日
Thanks, also a good solution :).

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

カテゴリ

Help Center および 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