Accessing Matrix Rows using Logical Indexing
12 views (last 30 days)
Show older comments
Kiran Ramaswamy
on 2 Mar 2011
Commented: Javier Cabello
on 16 May 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!
0 Comments
Accepted Answer
Matt Fig
on 2 Mar 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 Comments
Javier Cabello
on 16 May 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?
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!