How to use IF statements for matrices correctly?

23 visualizaciones (últimos 30 días)
Christian Reinicke
Christian Reinicke el 8 de Feb. de 2017
Editada: Jan el 8 de Feb. de 2017
I am trying to use an if statement to check if a specific matrix is a zero matrix. For the first 3 examples an if statement works correctly. However, in example for the if statement considers the statement to be true even though it is obviously wrong. What is going wrong here? Thanks for any help in advance! Chris
Example 1
if [1,1;1,1] ~= zeros(2)
disp('hello')
end
>>hello
Example 2
if [1,1;1,1] == zeros(2)
disp('hello')
end
>>
Example 3
if eye(2) == zeros(2)
disp('hello')
end
>>
Example 4
if eye(2) == zeros(2)
disp('hello')
end
>>hello
  1 comentario
Jan
Jan el 8 de Feb. de 2017
There is no difference between the 3rd and 4th example.

Iniciar sesión para comentar.

Respuestas (2)

Alexandra Harkai
Alexandra Harkai el 8 de Feb. de 2017
What MATLAB version are you using? Are you sure Example 4 gives a different result than Example 3?
This works 'properly', as in not displaying 'hello', as per the rules of if ("An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."):
if eye(2)==zeros(2), disp('hello'), end
You could utilise the isqeual function to do the same:
if isequal(eye(2), zeros(2)), disp('hello'), end

Jan
Jan el 8 de Feb. de 2017
Editada: Jan el 8 de Feb. de 2017
In your case, [1,1;1,1] == zeros(2) creates a 2x2 logical array. If the argument of an IF command is an array, Matlab converts it as this automatically to:
if all(Condition(:)) && ~isempty(Condition)
If you want to check for a "zero-matrix", prefer to do this explicitly:
if all(M(:)) && ismatrix(M)
This is easier to understand than using the automagic convertion.
Although
if isequal(X, zeros(2,2))
is valid, this wastes time by creating the temporary zero matrix. If you want to check, if all elements are zeros, prefer only to check if all elements are zeros. :-)

Categorías

Más información sobre Symbolic Math Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by