|Programming and Data Types|
This section covers the following topics:
Using break, continue, and return
It's easy to confuse the
return functions as they are similar in some ways. Make sure you use these functions appropriately.
||Where to Use It
||Exits the loop in which it appears. In nested loops, control passes to the next outer loop.
||Skips any remaining statements in the current loop. Control passes to next iteration of the same loop.
||Immediately exits the function in which it appears. Control passes to the caller of the function.
Using switch Versus if
It is possible, but usually not advantageous, to implement
case statements using
elseif instead. See pros and cons in the table.
|Easier to read
||Can be difficult to read
|Can compare strings of different lengths
|Test for equality only
||Test for equality or inequality
MATLAB case Evaluates Strings
A useful difference between
case statements in MATLAB and C is that you can specify string values in MATLAB
case statements, which you cannot do in C.
Multiple Conditions in a case Statement
You can test against more than one condition with
switch. The first case below tests for either a
bilinear method by using a cell array in the case statement.
Implicit Break in switch/case
In C, if you don't end each
case with a
break statement, code execution falls through to the following
case. In MATLAB,
case statements do not fall through; only one
case may execute. Using
break within a
case statement is not only unnecessary, it is also invalid and generates a warning.
In this example, if
52, only the first
disp statement executes, even though the second is also a valid match:
Variable Scope in a switch
Since MATLAB executes only one
case of any
switch statement, variables defined within one
case are not known in the other
cases of that
switch statement. The same holds true for
In these examples, you get an error when
x is undefined.
Catching Errors with try/catch
When you have statements in your code that could possibly generate unwanted results, put those statements into a
catch block that will catch any errors and handle them appropriately.
The example below shows a
catch block within a function that multiplies two matrices. If a statement in the
try segment of the block fails, control passes to the
catch segment. In this case, the
catch statements check the error message that was issued (returned by
lasterr) and respond appropriately.
For more information: See Checking for Errors with try-catch in the MATLAB "Programming and Data Types" documentation
Nested try/catch Blocks
You can also nest
catch blocks, as shown here. You can use this to attempt to recover from an error caught in the first
Forcing an Early Return from a Function
To force an early return from a function, place a
return statement in the function at the point where you want to exit. For example,
|MATLAB Path||Save and Load|