Accessing Matrix Rows using Logical Indexing

12 visualizaciones (últimos 30 días)
Kiran Ramaswamy
Kiran Ramaswamy el 2 de Mzo. de 2011
Comentada: Javier Cabello el 16 de Mayo de 2022
This is probably a very simple question to answer, and I'm sure its been asked a million times, but I just can't seem to find an answer that works for me.
Let's say I have an array like this:
A = [1 1 1 1;2 2 2 2;3 3 3 3;4 4 4 4];
A =
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
Now, I want to somehow return all the rows where the values in the second column are greater than 3.
I know I can get the logical indices like this:
B = A(:, 2) > 2;
B =
0
0
1
1
Now, if I then do this:
C = A(B);
C =
3
4
What I get back is a vector that contains the values from the first column who's rows correspond to the indices from B that are 1.
What I want instead though, is all four columns instead of just the first column.
C =
3 3 3 3
4 4 4 4
So far, the only way I know of to get this to work, is to use a for loop, like this:
counter = 1;
for i = 1:size(A, 1)
if (A(i, 2)) > 2
C(counter, :) = A(i, :);
counter = counter + 1;
end
end
This is kinda inefficient though, since it needs to loop through every element instead of using MATLAB's powerful array processing features.
Can someone tell me how to accomplish what I'm trying to, without using loops?
Thanks!

Respuesta aceptada

Matt Fig
Matt Fig el 2 de Mzo. de 2011
A = [1 1 1 1;2 2 2 2;3 3 3 3;4 4 4 4];
B = A(:, 2) > 2;
C = A(B,:);
Or for short:
C = A(A(:, 2) > 2,:);
  4 comentarios
Paul Safier
Paul Safier el 2 de Feb. de 2022
Great answer @Matt Fig thanks!
Javier Cabello
Javier Cabello el 16 de Mayo de 2022
That's so cool! I didn't know you could use logical indexing as a reference to matrix positions. Where can I read more of this?

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