Correct evaluation of a logical statement, incorrect result?
1 view (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
Dennis
on 5 Mar 2019
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;
More Answers (1)
Steven Lord
on 6 Mar 2019
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.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!