what will be displayd and why?
1 view (last 30 days)
Show older comments
-------------------------------------
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 Comment
Accepted Answer
Stephen23
on 13 Mar 2015
Edited: Stephen23
on 22 May 2015
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.
0 Comments
More Answers (2)
Image Analyst
on 13 Mar 2015
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 Comments
Adam
on 13 Mar 2015
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.
See Also
Categories
Find more on Axis Labels in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!