Correct evaluation of a logical statement, incorrect result?

조회 수: 1 (최근 30일)
Geoff Luck
Geoff Luck 2019년 3월 5일
댓글: Geoff Luck 2019년 3월 6일
Hi,
I’m trying to create a 96 x 6 matrix, using a logical if statement to select the desired combination of values derived from performing one of two different operations on an existing 96 x 6 matrix. Like this:
if A <= 0.4
B = C ./ D;
else B = C .* D;
end
For each element in the matrix, if an element in A is less than or equal to 0.4, divide the equivalent element in C by D; if an element in A is greater than 0.4, multiply the equivalent element in C by D.
A is a 96 x 6 matrix of values that vary from 0 to 2.
B is the final 96 x 6 matrix I’m seeking.
C is a 96 x 6 matrix.
D is a scalar.
The logical statement produces the correct combination of 0s and 1s to index the locations on which to perform the desired operation, but the final matrix is composed entirely of elements produced by C .* D.
Can anyone offer any suggestions?
Thanks!

채택된 답변

Dennis
Dennis 2019년 3월 5일
It would be helpful to see your code, to find any errors. This should work fine:
A=rand(96,6);
D=5;
B=zeros(96,6);
C=3*ones(96,6);
B((A<=0.4))=C(A<=0.4)./D;
B((A>0.4))=C(A>0.4)*D;

추가 답변 (1개)

Steven Lord
Steven Lord 2019년 3월 6일
As Dennis suggested, you should use logical indexing. But as for why this behaves the way it does:
For each element in the matrix, if an element in A is less than or equal to 0.4, divide the equivalent element in C by D; if an element in A is greater than 0.4, multiply the equivalent element in C by D.
That's not what the code you wrote does. The if statement is not any sort of looping construct. When you specify a non-scalar condition the documentation says:
"if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
The expression in your call is A <= 0.4 and that will only be nonempty and contain only nonzero elements if A is not empty and all the elements of A are less than 0.4. The if keyword doesn't run its statements just for those elements of the expression that are nonzero.
  댓글 수: 1
Geoff Luck
Geoff Luck 2019년 3월 6일
Many thanks for the extra detail, Steven! I realise now that logical indexing is what I needed, and have since implemented it elsewhere I was struggling. Thanks again!

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by