Select elements of a matrix using an array (of indices)
36 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Bruno Luong
le 22 Avr 2022
Modifié(e) : Bruno Luong
le 22 Avr 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(:)))'
3 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!