Programming in MATLAB

Function Files

When you need to repeat a set of commands several times defining a function file can be useful.
By creating a file with the extension .m you can write and run programs. To run your file you have to type its name in the command prompt.

The first line in a function file must begin with a function definition line. This  line distinguishes a function from a script file (both *.m files).
function [ output variables ] = function_name( input variables )

It is advisable to give the file the same name as the function name.

Unlike a script file, all the variables in a function file are local, that is, their values are available only within the function.
To create global variables the global command has to be used. This allows to share variables/values that are available to the workspace.

Example 1: mySum.m

mySum.m

 
function s = mySum( n )
% ===================================================
% Purpose: This function computes the sum from 1 to n.
% Syntax: s = mySum( n )
% Inputs: n = integer
% Output: s = result of summation
% ===================================================

% Initialize variable
s = 0;

% Check if number is positive
if ( n < 1 )
  return;
else
  % Accumulate values
  for i = 1:n
    s = s + i;
  end
end

>> myS = mySum( 5 )
 This should run just like any built-in MATLAB function.

Type
 
>>help mySum


MATLAB will print to the screen the comments which follow
the "function" declaration at the top of the file when the
help command is used.

To list the entire file type

>>type mySum

The variable s is being assigned the value of the summation.
The square brackets are optional when there is only one output.

function [ s ] = mySum( n )

Example 2: veldis.m

function [ dist, vel ] = veldis( v0, t )
%=================================================
% Purpose: This function computes the distance
%          traveled by a dropped object given
%          the initial velocity and the time.
% Syntax:  [ d, v ] = veldis( v0, t )
% Inputs:  v0 = double, velocity
%          t = double, time
% Output:  dist= double, distance
% vel =    double, velocity
% =================================================
g = 9.8;
vel = g*t + v0;
dist = 0.5* g* t.^2 + v0 * t;

We can run this function typing:

>> veldis( 2, 5 )
ans =132.5000
>> [ d, v ] = veldis( 2, 5 )
d =132.5000
v =51
>> v0 = 2
v0 =2
>> t= 5
t =5
>> [ d, v ] = veldis( v0, t )
d =132.5000
v =51

Sub-functions

A function may contain more than one user-defined function. The first defined function is called the primary function. All other functions in the file are called sub-functions. Sub-functions are visible to the primary function. Sub-functions are used to reduce the number of files that define a given function.

Structured-Programming

IF Statement

Branching is the construction

   if condition,
      program 
   end
or
   if condition , 
     program1; 
   else 
     program2; 
   end

or

   if condition1 
     program1; 
   elseif condition2, 
     program2;
   end

FOR Loops

A for loop is a construction of the form
  for i = 1:n, 
     program,
  end 
or
  for i = ind_0:step:ind_n 
    program;
  end

The program statements are repeated n times.

for i = [2, 4, 6, 10]
   statements;
end 

In this case, the statement part will be executed 4 times.


dotProd.m
function x = dotProd( a, b )
% ===========================================
% Purpose: compute the dot product of two vectors
% Syntax: x = dotProd( a, b )
% Inputs: a = vector
%         b = vector
% Output: x = a * b
% ===========================================

 m = length( a );
 k = length( b );
 if ( m~=k ),
   x = 'ERROR: vector dimensions do not agree';
   return,
 end %if
 x = 0;
 for i=1:m,
   x = a( i ) * b( i ) + x ;
 end %for

WHILE Loops

A while loop is a construction of the form

  while condition 
     program; 
  end

The program will execute successively as long as the value of condition is not false ( 0 ).

Scripts vs. Functions

There are 2 sorts of M-files: functions and scripts. When you call an M-file function MATLAB parses it and stores it in memory, so that on subsequent calls it runs faster. A function usually takes input arguments and returns some output. A function file must start with a "function" declaration. Functions make use of their own local variables. A script is an m-file without the function declaration at the top.