MATLAB: Correct evaluation of a logical statement, incorrect result

logical statementmatrices and scalars

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!

Best Answer

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;