What evaluates to "true" in matlab?
24 次查看(过去 30 天)
显示 更早的评论
I'm curious about the logic behind MATLAB's evaluation of logical casts, especially when using an if statement. For instance in the following:
if rand(5)
disp('True')
end
would normally reach the display statement, but if there was one zero anywhere in the array, it does not. This is a big deal if you are too lazy to write "isempty" in your tests.
I've also seen some buggy behavior in the following flavor:
>>> test = some > condition
>>> test
false
>>> ~test
false
>>> ~~test
true
>>> if test, disp("Got here"), end
Got here
Unfortunately I can't produce a canonical example for this condition; it just happened in some project code. That was very disconcerting. Even worse was that it errored on a two Macs, but not on a Ubuntu box.
So the question is, how does the "if" statement decide what cast to perform, or any array operations, or any other magic?
0 个评论
回答(3 个)
Matt Fig
2011-4-25
For the first part of your question, IF statements on vectors evaluate to true only if all of the elements in the vector would evaluate to true.
A = [1 1 0];
if A,disp('InIf1'),end
A(3) = true;
if A,disp('InIf2'),end
This can be useful, if you are aware of it, and jarring if you are not! This syntax means you don't have to use an ALL statement if you want that behavior.
As for the second part, Oleg has pointed you to some blog posts about the behavior of empty arrays with IF statements, but I wonder if that is what you are seeing given the code you show - an empty array wouldn't do that. Please post an example of what is in 'test' above. If you can't post it, at least describe it. Is it an array or a scalar? Is if of type double, logical or what?
0 个评论
Oleg Komarov
2011-4-25
http://blogs.mathworks.com/loren/2009/11/12/empty-arrays-with-flow-of-control-and-logical-operators/
test = some > condition
false
~test
false
Very very suspicious, especially if you can't reproduce it.
0 个评论
Steve Eddins
2011-4-25
I don't have anything substantial to add to the previous answers, but I wanted to point out that the behavior of IF for nonscalar expressions is thoroughly and clearly documented. See this doc page, where it says:
An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.
There are no casts, array operations, or magic involved.
My personal practice is to always use scalar expressions in if and while conditional contexts.
Also, like Oleg, I am very skeptical of the report of buggy behavior.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!