Using a logic mask for selective data operations

조회 수: 60 (최근 30일)
Wah On Ho
Wah On Ho 2019년 12월 18일
댓글: Star Strider 2019년 12월 18일
Hi All. I'm trying to use a logic mask to select data in a numerical matrix, rather than simply looping through each cell, and perform some mathematical operation, and then the inverse maks to perform a different operation. For example...
data = [-2, -4, 1, 3, 4, -6; -0.5, 2.4, 5, 9.8, 3, -11.2; 4, 3, -2, -1.5, 7, 10; 3, 4, -2.4, -3.3, -8, 10];
logicmaskneg = data < 0;
logicmaskpos = data > 0;
dataneg = data(logicmaskneg);
datapos = data(logicmaskpos);
So logicmaskneg and logicmaskpos keep the same matrix structure as data. But dataneg and datapos collapses the data matrix into one column. How do I apply the logic masks such that I can keep dataneg and datapos in the matrix organisation as data so I can continue to perform further calculations preserving the original column and row organisation?
Maybe I'm going about this the wrong way. My aim is to perform one operation on only the negative numbers and a different calculation on the positive numbers while preserving the data layout.
Any help and advice is much appreciated.
Thanks.

채택된 답변

Star Strider
Star Strider 2019년 12월 18일
The ‘logicmaskneg’ and ‘logicmaskpos’ matrices become numeric matrices when used in any calculation.
See if this does whatt you want:
data = [-2, -4, 1, 3, 4, -6; -0.5, 2.4, 5, 9.8, 3, -11.2; 4, 3, -2, -1.5, 7, 10; 3, 4, -2.4, -3.3, -8, 10];
logicmaskneg = data < 0;
logicmaskpos = data > 0;
dataneg = data(logicmaskneg);
datapos = data(logicmaskpos);
producing:
dataneg =
-2 -4 0 0 0 -6
-0.5 0 0 0 0 -11.2
0 0 -2 -1.5 0 0
0 0 -2.4 -3.3 -8 0
datapos =
0 0 1 3 4 0
0 2.4 5 9.8 3 0
4 3 0 0 7 10
3 4 0 0 0 10
  댓글 수: 8
Wah On Ho
Wah On Ho 2019년 12월 18일
That's exactly what I'm after! I agree, Matlab does make these calculations straightforward once you know. Thank you so much.
Star Strider
Star Strider 2019년 12월 18일
As always, my pleasure!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by