logical indexing

3 visualizaciones (últimos 30 días)
Thijs
Thijs el 14 de Mzo. de 2012
imagine you have a two matrixes:
a=[1 2 3 4 5 6 7 8 9];
b=[1 0 1 0 1];
how do i use the b matrix as a logical index? I'd expect:
a(b)
ans =
[1 3 5]
but instead i get the error: "Subscript indices must either be real positive integers or logicals."
if I try
a(~b)
ans =
[2 4]
now I could use a(~~b) which does what i want but this seems inelegant. Can anyone suggest a better solution?

Respuesta aceptada

Jacob Halbrooks
Jacob Halbrooks el 14 de Mzo. de 2012
Use LOGICAL to do the type conversion:
a(logical(b))

Más respuestas (4)

Aldin
Aldin el 14 de Mzo. de 2012
Here:
for i = 1:5
if b(i) == 1
disp(a(i))
end
end
:)
  6 comentarios
Aldin
Aldin el 14 de Mzo. de 2012
result =
1 3 5
Aldin
Aldin el 14 de Mzo. de 2012
Here is another solution:
a(b(1:5)==1)

Iniciar sesión para comentar.


Thijs
Thijs el 14 de Mzo. de 2012
a(logical(b)) does what I want. In case anyone else is wondering
  2 comentarios
Aldin
Aldin el 14 de Mzo. de 2012
See above it's similiar with my solution :)
Thijs
Thijs el 14 de Mzo. de 2012
true, thanks

Iniciar sesión para comentar.


Onomitra Ghosh
Onomitra Ghosh el 14 de Mzo. de 2012
Your "b" matrix is in double. You need to convert that to logical values for logical indexing:
>> a(boolean(b))
ans =
1 3 5

Aldin
Aldin el 14 de Mzo. de 2012
but what if you haven't only '1' and '0' in b array. I think it's better my first solution or second &Onomitra Ghosh his code with logical work correctly

Categorías

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

Etiquetas

Aún no se han introducido etiquetas.

Community Treasure Hunt

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

Start Hunting!

Translated by