Indexing matrix with multiplication

7 views (last 30 days)
user20912 on 27 Nov 2023
Commented: user20912 on 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;
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;
Thanks

Cris LaPierre on 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 = 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
ans = 13×1
48 21 27 35 26 38 45 42 42 34
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 CommentsShow 1 older commentHide 1 older comment
Walter Roberson on 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 = 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 = 15×1
22 39 48 45 47 38 42 45 33 30
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 on 27 Nov 2023
Thank you.

Matt J on 27 Nov 2023
Edited: Matt J on 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
ans = 5×1
24 26 23 24 30
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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2023b

Community Treasure Hunt

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

Start Hunting!