Index multiple elements in a vector using logical indexing
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rob
el 28 de Mzo. de 2011
Respondida: Vasileios Siomos
el 25 de Mzo. de 2017
Hi, I want to use logical indexing to "grap" some elements from a vector. Normally if you're only looking for a single element, you could use the "find" function, for example:
A = [1 2 3 4 5 6];
B = 2;
C = [5 6 7 8 9 0]
D = C(find(A==B));
or use something like: D = C(A==B);
But now I am interested in finding multiple elements in A. So B becomes a vector in this case. For example:
A = [1 2 3 4 5 6];
B = [2 4];
C = [5 6 7 8 9 0]
I thought I could do something simular as in the upper case, by writing something like:
D = C(A==B). But apparently this does noet work.
Can anyone help me? Thanks a lot in advance!
2 comentarios
Matt Tearle
el 28 de Mzo. de 2011
Indeed! Good question, and good answers. A good community exchange all round!
(It was a Q&A of two halves, the comment with the most votes won, but MATLAB Answers was the real winner on the day. Ahhh, my cliche-o-matic is stuck...)
Respuesta aceptada
Sean de Wolski
el 28 de Mzo. de 2011
Oleg's way is probably faster, but also:
D = C(any(bsxfun(@eq,A.',B),2))
Más respuestas (2)
Oleg Komarov
el 28 de Mzo. de 2011
For comparison with multiple elements:
D = C(ismember(A,B))
Also, avoid to use find when you don't need the coordinates.
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices 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!