Correct evaluation of a logical statement, incorrect result?

2 visualizaciones (últimos 30 días)
Geoff Luck
Geoff Luck el 5 de Mzo. de 2019
Comentada: Geoff Luck el 6 de Mzo. de 2019
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!

Respuesta aceptada

Dennis
Dennis el 5 de Mzo. de 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;

Más respuestas (1)

Steven Lord
Steven Lord el 6 de Mzo. de 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.
  1 comentario
Geoff Luck
Geoff Luck el 6 de Mzo. de 2019
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!

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by