Indexing matrix with multiplication

2 visualizzazioni (ultimi 30 giorni)
user20912
user20912 il 27 Nov 2023
Commentato: user20912 il 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

Risposta accettata

Cris LaPierre
Cris LaPierre il 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 Commenti
Walter Roberson
Walter Roberson il 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

Accedi per commentare.

Più risposte (1)

Matt J
Matt J il 27 Nov 2023
Modificato: Matt J il 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

Prodotti


Release

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by