Indexing matrix with multiplication

2 Ansichten (letzte 30 Tage)
user20912
user20912 am 27 Nov. 2023
Kommentiert: user20912 am 27 Nov. 2023
Hi,
it is the same to apply a mask as an index or multiplying?
Say, I've a 2D matrix T. When I need the values that obey some condition I normally use an index as:
mask = T > 20;
T(mask)
Recently, I came across the problem that I need to keep the dimensions of the original matrix when I apply the index. Hence my question, is the previous code example the same as the following?
mask = T > 20;
T.*mask
Thanks

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 27 Nov. 2023
It's not exactly the same. To keep the dimensions, the second option places a zero in each location that does not meet the mask criteria.
T = randi(50,5)
T = 5×5
48 26 42 16 11 13 13 2 3 3 21 38 19 42 19 27 4 17 34 39 35 45 19 21 26
mask = T>20
mask = 5×5 logical array
1 1 1 0 0 0 0 0 0 0 1 1 0 1 0 1 0 0 1 1 1 1 0 1 1
T(mask)
ans = 13×1
48 21 27 35 26 38 45 42 42 34
T.*mask
ans = 5×5
48 26 42 0 0 0 0 0 0 0 21 38 0 42 0 27 0 0 34 39 35 45 0 21 26
  3 Kommentare
Walter Roberson
Walter Roberson am 27 Nov. 2023
T = randi(50,5)
T = 5×5
22 9 38 30 43 17 45 42 47 37 16 47 1 14 31 39 20 45 31 20 48 15 33 12 7
mask = T>20
mask = 5×5 logical array
1 0 1 1 1 0 1 1 1 1 0 1 0 0 1 1 0 1 1 0 1 0 1 0 0
out1 = T(mask)
out1 = 15×1
22 39 48 45 47 38 42 45 33 30
out2 = T.*mask
out2 = 5×5
22 0 38 30 43 0 45 42 47 37 0 47 0 0 31 39 0 45 31 0 48 0 33 0 0
out3 = nonzeros(out2)
out3 = 15×1
22 39 48 45 47 38 42 45 33 30
isequal(out1, out3)
ans = logical
1
user20912
user20912 am 27 Nov. 2023
Thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Matt J
Matt J am 27 Nov. 2023
Bearbeitet: Matt J am 27 Nov. 2023
No. You can easily see they are not the same by comparing them yourself:
T=randi(30,5)
T = 5×5
13 7 1 23 19 24 3 26 4 24 17 18 11 10 18 7 6 5 17 30 2 8 16 12 6
mask=T>20;
T(mask)
ans = 5×1
24 26 23 24 30
T.*mask
ans = 5×5
0 0 0 23 0 24 0 26 0 24 0 0 0 0 0 0 0 0 0 30 0 0 0 0 0

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by