| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Conditional Control — if, else, switch |
This section covers those MATLAB product functions that provide conditional program control.
The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords—no braces or brackets are involved.
The MATLAB algorithm for generating a magic square of order n involves three different cases: when n is odd, when n is even but not divisible by 4, or when n is divisible by 4. This is described by
if rem(n,2) ~= 0 M = odd_magic(n) elseif rem(n,4) ~= 0 M = single_even_magic(n) else M = double_even_magic(n) end
For most values of n in this example, the three cases are mutually exclusive. For values that are not mutually exclusive, such as n=5, the first true condition is executed.
It is important to understand how relational operators and if statements work with matrices. When you want to check for equality between two variables, you might use
if A == B, ...
This is valid MATLAB code, and does what you expect when A and B are scalars. But when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's showing element-by-element equality. (In fact, if A and B are not the same size, then A == B is an error.)
A = magic(4); B = A; B(1,1) = 0;
A == B
ans =
0 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1The proper way to check for equality between two variables is to use the isequal function:
if isequal(A, B), ...
isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix, as the expression to be evaluated by the if function. Using the A and B matrices from above, you get
isequal(A, B)
ans =
0Here is another example to emphasize this point. If A and B are scalars, the following program will never reach the "unexpected situation". But for most pairs of matrices, including our magic squares with interchanged columns, none of the matrix conditions A > B, A < B, or A == B is true for all elements and so the else clause is executed:
if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
endSeveral functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including
isequal isempty all any
The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch.
The logic of the magic squares algorithm can also be described by
switch (rem(n,4)==0) + (rem(n,2)==0)
case 0
M = odd_magic(n)
case 1
M = single_even_magic(n)
case 2
M = double_even_magic(n)
otherwise
error('This is impossible')
endNote Unlike the C language switch statement, the MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required. |
This section covers those MATLAB functions that provide control over program loops.
The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements:
for n = 3:32 r(n) = rank(magic(n)); end r
The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop displays the final result.
It is a good idea to indent the loops for readability, especially when they are nested:
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
endThe while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.
Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial:
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
xThe result is a root of the polynomial x3 - 2x - 5, namely
x = 2.09455148154233
The cautions involving matrix comparisons that are discussed in the section on the if statement also apply to the while statement.
The continue statement passes control to the next iteration of the for loop or while loop in which it appears, skipping any remaining statements in the body of the loop. The same holds true for continue statements in nested loops. That is, execution continues at the beginning of the loop in which the continue statement was encountered.
The example below shows a continue loop that counts the lines of code in the file magic.m, skipping all blank lines and comments. A continue statement is used to advance to the next line in magic.m without incrementing the count whenever a blank line or comment line is encountered:
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) || strncmp(line,'%',1) || ~ischar(line)
continue
end
count = count + 1;
end
fprintf('%d lines\n',count);
fclose(fid);The break statement lets you exit early from a for loop or while loop. In nested loops, break exits from the innermost loop only.
Here is an improvement on the example from the previous section. Why is this use of break a good idea?
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
xThis section covers those MATLAB functions that provide error handling control.
The general form of a try-catch statement sequence is
try statement ... statement catch exceptObj statement ... statement end
In this sequence, the statements in the try block (that part of the try-catch that follows the word try statement, and precedes catch) between try and catch execute just like any other program code. If an error occurs within the try section The statements between catch and end are then executed. Examine the contents of the MException object exceptObj to see the cause of the error. If an error occurs between catch and end, MATLAB terminates execution unless another try-catch sequence has been established.
This section covers the MATLAB return function that enables you to terminate your program before it runs to completion.
return terminates the current sequence of commands and returns control to the invoking function or to the keyboard. return is also used to terminate keyboard mode. A called function normally transfers control to the function that invoked it when it reaches the end of the function. You can insert a return statement within the called function to force an early termination and to transfer control to the invoking function.
![]() | Programming | Other Data Structures | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |