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

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

 Accepted Answer

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

3 Comments

Thanks a lot @Bruno Luong!!
Would it be possible to use the same solution you have proposed when I have zeros in A and in I ?
Indeed, if I have some zeros in both A and I, I get the following error:
% Input
A =[ 0 0
3850 3886
0 0
0 0
0 0
0 0
0 0
0 3856
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
3887 3831
0 0
0 0
0 0
0 0
0 0
0 0
0 0
3879 3812
3878 3847
3796 3885
0 0];
I =[ 0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
0
0
0
0
0
0
2
2
1
0];
B = A(sub2ind(size(A), (1:size(A,1))', I(:)))'
% Output
Error using sub2ind (line 55)
Out of range subscript.
Error in untitled2 (line 66)
B = A(sub2ind(size(A), (1:size(A,1))', I(:)))'
No MATLAB is 1-based indexing.
ah ok, many thanks!!

Sign in to comment.

More Answers (0)

Asked:

Sim
on 22 Apr 2022

Commented:

Sim
on 22 Apr 2022

Community Treasure Hunt

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

Start Hunting!