フィルターのクリア

How to check adjacent data with logical indexing?

5 ビュー (過去 30 日間)
Daniel H
Daniel H 2021 年 9 月 9 日
コメント済み: Daniel H 2021 年 9 月 11 日
How can I select matrix entries which have a certain criteria and are adjacent to entries having another criteria? (with logical indexing!)
Suppose I have a matrix and I first use logical indexing to select all elements which are greater than a certain number, say 20:
A=magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
idx1=A>20
idx1 =
5×5 logical array
0 1 0 0 0
1 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
Now I would like to select all entries which (1) are adjacent to those and (2) are greater than a certain (different) number, say 18.
I can select the left and right elements with:
K>> idx1_right = circshift(idx1,1,2)
idx1_right =
5×5 logical array
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0
0 0 0 0 1
0 0 0 1 0
K>> idx1_left = circshift(idx1,-1,2)
idx1_left =
5×5 logical array
1 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
However, how can I combine these logical index matrices with another logical query?
Like
idx2 = A(idx1_left)>18 | A(idx1_right)>18;
?
This does not work because it just A(idx1_left) returns a vector with the matching elements and hence idx2 as a whole is a vector which is incompatible with the size of A.

採用された回答

Chunru
Chunru 2021 年 9 月 9 日
編集済み: Chunru 2021 年 9 月 9 日
A=magic(5)
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
idx1=A>20
idx1 = 5×5 logical array
0 1 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0
idx1_right = circshift(idx1,1,2)
idx1_right = 5×5 logical array
0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 1 0
idx1_left = circshift(idx1,-1,2)
idx1_left = 5×5 logical array
1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0
idx2 = idx1 & (A(idx1_left)>18 | A(idx1_right)>18) % is this what you want?
idx2 = 5×5 logical array
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0
  1 件のコメント
Daniel H
Daniel H 2021 年 9 月 11 日
Oh yes, so simple. Thank you!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by