How to check adjacent data with logical indexing?

5 次查看(过去 30 天)
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 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by