How to use IF statements for matrices correctly?

22 ビュー (過去 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
  1 件のコメント
Stephen23
Stephen23 2017 年 2 月 8 日
+1 for isequal

サインインしてコメントする。


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 Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by