Conditional calculations on a numeric matrix

조회 수: 12 (최근 30일)
Wah On Ho
Wah On Ho 2019년 11월 18일
댓글: Walter Roberson 2019년 11월 18일
Hi All,
I'm relatively new to Matlab and I find myself slightly stuck. I have a numeric matrix of numbers comprising of floating point values. Depending on whether the value in each cell is less than or greater than some threshold value, either one or another calculation is made.
Below is a much simplified expression of my problem but it illustrates the form of what I'm trying to do with millions of cells of values which takes a rather longer time than the illustration below.
I realise that I can make a logic matrix from the input matrix but then I'm stuck on what follows to complete the calculations.
Any advice is gratefully received.
input = magic(10);
thresholdvalue = 50;
for col = 1 : 10
for row = 1 : 10
if input(row,col) > thresholdvalue
result(row,col) = input(row,col)*2;
else
result(row,col) = input(row,col)/2;
end
end
end

채택된 답변

Walter Roberson
Walter Roberson 2019년 11월 18일
mask = input > thresholdvalue;
result(mask) = input(mask) * 2;
result(~mask) = input(mask) / 2;
  댓글 수: 2
Wah On Ho
Wah On Ho 2019년 11월 18일
Dear Walter,
That's excellent - thank you! So simple yet so effective.
The result from the 3rd line initially confused me as it didn't output a result that was divided by 2 until I realised its missing the tilde for the inverse mask for input(~mask) / 2. Anyway I'm now unstuck and can progress.
Walter Roberson
Walter Roberson 2019년 11월 18일
Ah, yes, sorry, I did have a typo there.
result(~mask) = input(~mask) / 2;

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by