5.2 Branching

Branching is the construction

if condition, program end
Here condition is a MATLAB function and program is a program segment. The entire construction executes the i>program just in case the value of condition is not 0. If that value is 0, the control moves on to the next program construction. You should keep in mind that MATLAB regards a==b and a<=b with values 0 or 1. Below are two more variations.

if condition,
   program1
else
   program2
end
In this case, if condition is 0, then program2 is executed.

if condition1,
    program1
  elseif condition2
    program2
  end
This time if condtion1 is not 0, then program1 is executed. If condition1 is 0 and if condition2 is not 0, then program2 is executed. Otherwise control is passed on to the next construction. Here is a short program to illustrate branching.

function b=even(n)

% b=even(n). If n is an even integer,
% then b=1, otherwise b=0.

if mod(n,2)==0,
   b=1;
   else b=0;
end


Next Section: 5.3 For Loops


Created by F.G. Garvan (fgarvan@ufl.edu) on Wed, Oct 01, 97
Last update made Thu Oct 2 11:22:21 EDT 1997.
Back to 5. Programming in Matlab
Back to Table of Contents
EMAIL: fgarvan@ufl.edu fgarvan@ufl.edu