Filter löschen
Filter löschen

How to check adjacent data with logical indexing?

5 Ansichten (letzte 30 Tage)
Daniel H
Daniel H am 9 Sep. 2021
Kommentiert: Daniel H am 11 Sep. 2021
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.

Akzeptierte Antwort

Chunru
Chunru am 9 Sep. 2021
Bearbeitet: Chunru am 9 Sep. 2021
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

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by