Accessing Matrix Rows using Logical Indexing

12 ビュー (過去 30 日間)
Kiran Ramaswamy
Kiran Ramaswamy 2011 年 3 月 2 日
コメント済み: Javier Cabello 2022 年 5 月 16 日
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!

採用された回答

Matt Fig
Matt Fig 2011 年 3 月 2 日
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 件のコメント
Paul Safier
Paul Safier 2022 年 2 月 2 日
Great answer @Matt Fig thanks!
Javier Cabello
Javier Cabello 2022 年 5 月 16 日
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?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by