23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Program Control<br />

through; only one case may execute. Using break within a case statement is<br />

not only unnecessary, it is also invalid and generates a warning.<br />

In this example, if result is 52, onlythefirstdisp statement executes, even<br />

though the second is also a valid match:<br />

switch(result)<br />

case 52<br />

disp('result is 52')<br />

case {52, 78}<br />

disp('result is 52 or 78')<br />

end<br />

Variable Scope in a switch<br />

Since <strong>MATLAB</strong> executes only one case of any switch statement, variables<br />

defined within one case arenotknownintheothercases of that switch<br />

statement. The same holds true for if-elseif statements.<br />

In these examples, you get an error when choice equals 2, becausex is<br />

undefined.<br />

-- SWITCH-CASE -- -- IF-ELSEIF --<br />

switch choice<br />

case 1 if choice == 1<br />

x = -pi:0.01:pi;<br />

x = -pi:0.01:pi;<br />

case 2 elseif choice == 2<br />

plot(x, sin(x));<br />

plot(x, sin(x));<br />

end<br />

end<br />

Catching Errors with try-catch<br />

When you have statements in your code that could possibly generate<br />

unwanted results, put those statements into a try-catch block that will catch<br />

any errors and handle them appropriately.<br />

The example below shows a try-catch block within a function that multiplies<br />

two matrices. If a statement in the try segment of the block fails, control<br />

passes to the catch segment. In this case, the catch statements check<br />

the error message that was issued (returned by lasterr) andrespond<br />

appropriately.<br />

12-41

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

Saved successfully!

Ooh no, something went wrong!