MATLAB: Accessing Matrix Rows using Logical Indexing

logical indexingmatrix

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!

Best Answer

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,:);