Short-Circuit Operators
The following operators perform AND and OR operations on logical expressions containing scalar values.
They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
The statement shown here performs an AND of two logical terms, A and B:
A && B
If A equals zero, then the entire expression will evaluate to logical 0 (false), regardless of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known. In this case, MATLAB short-circuits the statement by evaluating only the first term.
A similar case is when you OR two terms and the first term is true. Again, regardless of the value of B, the statement will evaluate to true. There is no need to evaluate the second term, and MATLAB does not do so.
Advantage of Short-Circuiting.
You can use the short-circuit operators to evaluate an expression only when certain conditions are satisfied. For example, you want to execute an M-file function only if the M-file resides on the current MATLAB path.
Short-circuiting keeps the following code from generating an error when the file, myfun.m, cannot be found:
comp = (exist('myfun.m') == 2) && (myfun(x) >= y)
Similarly, this statement avoids divide-by-zero errors when b equals zero:
x = (b ~= 0) && (a/b > 18.5)
You can also use the && and || operators in if and while statements to take advantage of their short-circuiting behavior:
if (nargin >= 3) && (ischar(varargin{3}))
浙公网安备 33010602011771号