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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by