How to use IF statements for matrices correctly?

조회 수: 23 (최근 30일)
Christian Reinicke
Christian Reinicke 2017년 2월 8일
편집: Jan 2017년 2월 8일
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
Jan
Jan 2017년 2월 8일
There is no difference between the 3rd and 4th example.

댓글을 달려면 로그인하십시오.

답변 (2개)

Alexandra Harkai
Alexandra Harkai 2017년 2월 8일
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 2017년 2월 8일
편집: Jan 2017년 2월 8일
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. :-)

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by