Control Flow & Logic
If Else:
if(condition)
...body
elseif(condition)
...body
else
...body
end
While
while (condition)
...body
continue // skip this step
break // exit Loop
end
Loop
- use continue to skip step
- use break to exit loop
for v = start: step : end
...body
continue // skip this step
break // exit Loop
end
Switch Case
-
MATLAB executes only one case of any switch statement: If the first case statement is true, MATLAB does not execute the other case statements.
-
Variables defined within one case are not available for other cases.
-
case_expression must be a scalar, a character vector, or a cell array of scalars or character vectors.
-
switch_expression must be a scalar or character vector
switch switch_expression
case case_expression
...body
case {case_expression1, case_expression2} // Fall Through
...body
otherwise
warning('Unexpected plot type. No plot created.')
end
Try Catch flow
-
You cannot use multiple catch blocks within a try block, but you can nest complete try/catch blocks.
-
MATLAB does not allow the use of a finally block within try/catch statements.
try
...body
catch ME
switch ME.identifier
case 'MATLAB:UndefinedFunction'
warning('Function is undefined. Assigning a value of NaN.');
case 'MATLAB:scriptNotAFunction'
warning(['Attempting to execute script as function. '...
'Running script and assigning output a value of 0.']);
otherwise
rethrow(ME)
end
end
