Accessing Matrix Rows using Logical Indexing

12 Ansichten (letzte 30 Tage)
Kiran Ramaswamy
Kiran Ramaswamy am 2 Mär. 2011
Kommentiert: Javier Cabello am 16 Mai 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!

Akzeptierte Antwort

Matt Fig
Matt Fig am 2 Mär. 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 Kommentare
Paul Safier
Paul Safier am 2 Feb. 2022
Great answer @Matt Fig thanks!
Javier Cabello
Javier Cabello am 16 Mai 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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by