How to use IF statements for matrices correctly?

23 Ansichten (letzte 30 Tage)
Christian Reinicke
Christian Reinicke am 8 Feb. 2017
Bearbeitet: Jan am 8 Feb. 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 Kommentar
Jan
Jan am 8 Feb. 2017
There is no difference between the 3rd and 4th example.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Alexandra Harkai
Alexandra Harkai am 8 Feb. 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 am 8 Feb. 2017
Bearbeitet: Jan am 8 Feb. 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. :-)

Kategorien

Mehr zu Symbolic Math Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by