# Select elements of a matrix using an array (of indices)

7 views (last 30 days)
Sim on 22 Apr 2022
Commented: Sim on 22 Apr 2022
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

Bruno Luong on 22 Apr 2022
Edited: Bruno Luong on 22 Apr 2022
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(:)))'
B = 1×12
164 2801 410 24 556 498 246 394 873 702 1027 109
Sim on 22 Apr 2022
ah ok, many thanks!!