Select elements of a matrix using an array (of indices)
36 ビュー (過去 30 日間)
古いコメントを表示
Hi, I have a matrix composed of 2 columns, called A, and an array of "indices", called I.
For each row of A, I would like to select the element in the first or in the second column, according to the number, 1 or 2, contained in the array I. This means, if I have the number 1 in the array I, I would select the element in the first column of A. Viceversa, if I have the number 2 in the array I, I would select the element in the second column of A.
It is a very silly question, but can I select the elements of A, just using I as indeces, instead of a loop ?
Something like this ?
B = A(:,I)
This is my example:
% Input
A =
164 101
2733 2801
323 410
20 24
556 494
498 345
59 246
394 341
873 870
627 702
923 1027
109 106
I =
1
2
2
2
1
1
2
1
1
2
2
1
% Desired Output
B' =
164
2801
410
24
556
498
246
394
873
702
1027
109
% Note: I used this loop to get B, but I would like to avoid it, and use something like B = A(:,I)
for i = 1 : size(A,1)
B(i) = A(i,I(i));
end
0 件のコメント
採用された回答
Bruno Luong
2022 年 4 月 22 日
編集済み: Bruno Luong
2022 年 4 月 22 日
A=[164 101
2733 2801
323 410
20 24
556 494
498 345
59 246
394 341
873 870
627 702
923 1027
109 106];
I =[1
2
2
2
1
1
2
1
1
2
2
1];
B = A(sub2ind(size(A), (1:size(A,1))', I(:)))'
3 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!