Indexing matrix with multiplication

조회 수: 2 (최근 30일)
user20912
user20912 2023년 11월 27일
댓글: user20912 2023년 11월 27일
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

채택된 답변

Cris LaPierre
Cris LaPierre 2023년 11월 27일
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
Walter Roberson
Walter Roberson 2023년 11월 27일
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 2023년 11월 27일
Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2023년 11월 27일
편집: Matt J 2023년 11월 27일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by