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 />

Program Control Statements<br />

Program control is divided into these four categories:<br />

• “Conditional Control — if, switch” on page 3-88<br />

• “Loop Control — for, while, continue, break” on page 3-92<br />

• “Error Control — try, catch” on page 3-95<br />

• “Program Termination — return” on page 3-96<br />

Note You can often speed up the execution of <strong>MATLAB</strong> code by replacing<br />

for and while loops with vectorized code. See “Techniques for Improving<br />

Performance” on page 11-4 for more information on this.<br />

Conditional Control — if, switch<br />

This group of control statements enables you to select at run-time which block<br />

of code is executed. To make this selection based on whether a condition is true<br />

or false, use the if statement (which may include else or elseif). To select<br />

from a number of possible options depending on the value of an expression,<br />

use the switch and case statements (which may include otherwise).<br />

if, else, and elseif<br />

if evaluates a logical expression and executes a group of statements based on<br />

thevalueoftheexpression.Inits simplest form, its syntax is<br />

if logical_expression<br />

statements<br />

end<br />

If the logical expression is true (that is, if it evaluates to logical 1), <strong>MATLAB</strong><br />

executes all the statements between the if and end lines. It resumes<br />

execution at the line following the end statement. If the condition is false<br />

(evaluates to logical 0), <strong>MATLAB</strong> skips all the statements between the if and<br />

end lines, and resumes execution at the line following the end statement.<br />

For example,<br />

3-88

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

Saved successfully!

Ooh no, something went wrong!