How to use IF statements for matrices correctly?
23 次查看(过去 30 天)
显示 更早的评论
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
回答(2 个)
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
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. :-)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!