-------------------------------------
if (x)
disp('true');
else
disp('false');
end;
if (~x)
disp('true');
else
disp('false');
end;
----------------------------------------
For the case x=[0 0 0 0]
and for the case x=[0 1 0 1]

댓글 수: 1

Adam
Adam 2015년 3월 13일
편집: Adam 2015년 3월 13일
Can't you just run the code to find out what is displayed?
You should generally use either 'all' or 'any' around a vector of logicals in an if statement though to avoid unexpected behaviour.

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

 채택된 답변

Stephen23
Stephen23 2015년 3월 13일
편집: Stephen23 2015년 5월 22일

0 개 추천

This is explained quite clearly in the if documentation: "An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
Which means:
  • [0,0,0,0] is false: all values are zero
  • [0,1,0,1] is false: some values are zero
  • ~[0,0,0,0]=[1,1,1,1] is true: contains only nonzero elements
  • ~[0,1,0,1]=[1,0,1,0] is false: some values are zero
Note that the definition defines a true expression as "contains only nonzero elements" but does not give an upper-limit to the number of nonzero elements.

추가 답변 (2개)

David Shapiro
David Shapiro 2015년 3월 13일

0 개 추천

i did it but i did not understand why i got what i got. its a question from a quiz i had.
Image Analyst
Image Analyst 2015년 3월 13일

0 개 추천

The all zero case is obvious. x=[0 0 0 0] is false no matter how you look at it - no way it can be true.
But if you have a case like [1 2 0 1] or [0 1 0 1] or [1,2,3,4], it will be true only if ALL of the elements are non-zero.

댓글 수: 2

David Shapiro
David Shapiro 2015년 3월 13일
but what is the condition " if x" means?
In this case (a vector) it seems to be shorthand for
if ( all(x) )
though I never tend to use that shorthand myself as I prefer the explicit use of all or any when using logicals for an if statement.

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

질문:

2015년 3월 13일

편집:

2015년 5월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by