23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3 Basic Program Components<br />

Advantage of Short-Circuiting. You can use the short-circuit operators<br />

to evaluate an expression only when certain conditions are satisfied. For<br />

example, you want to execute an M-file function only if the M-file resides on<br />

the current <strong>MATLAB</strong> path.<br />

Short-circuiting keeps the following code from generating an error when the<br />

file, myfun.m, cannot be found:<br />

comp = (exist('myfun.m') == 2) && (myfun(x) >= y)<br />

Similarly, this statement avoids divide-by-zero errors when b equals zero:<br />

x = (b ~= 0) && (a/b > 18.5)<br />

You can also use the && and || operators in if and while statements to take<br />

advantage of their short-circuiting behavior:<br />

if (nargin >= 3) && (ischar(varargin{3}))<br />

Operator Precedence<br />

You can build expressions that use any combination of arithmetic, relational,<br />

and logical operators. Precedence levels determine the order in which<br />

<strong>MATLAB</strong> evaluates an expression. Within each precedence level, operators<br />

have equal precedence and are evaluated from left to right. The precedence<br />

rules for <strong>MATLAB</strong> operators are shown in this list, ordered from highest<br />

precedence level to lowest precedence level:<br />

1 Parentheses ()<br />

2 Transpose (.'), power (.^), complex conjugate transpose (’), matrix power<br />

(^)<br />

3 Unary plus (+), unary minus (-), logical negation (~)<br />

4 Multiplication (.*), right division (./), left division (.\), matrix<br />

multiplication (*), matrix right division (/), matrix left division (\)<br />

5 Addition (+), subtraction (-)<br />

6 Colon operator (:)<br />

3-26

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!