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

20 visualizaciones (últimos 30 días)
Sim
Sim el 22 de Abr. de 2022
Comentada: Sim el 22 de Abr. de 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

Respuesta aceptada

Bruno Luong
Bruno Luong el 22 de Abr. de 2022
Editada: Bruno Luong el 22 de Abr. de 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
  3 comentarios
Bruno Luong
Bruno Luong el 22 de Abr. de 2022
No MATLAB is 1-based indexing.
Sim
Sim el 22 de Abr. de 2022
ah ok, many thanks!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by