Introduction to Matlab

Mathematics University of Queensland Mathematics

9  Functions

Often we need to work with functions. For example, we may want to find the minimum of a function, its zeros, or the definite integral of the function. This section explains how to create functions and work with them in Matlab.

9.1  Writing a Function

To set up functions in Matlab, we need to create a file containing the Matlab code that evaluates the function. These files are called function files. The name of the file must always end with the `.m' extension (for example fred.m, funct.m, etc.). Suppose we need to work with the function
f(x) = 1
(x-.3)2+.01
+ 1
(x-.9)2+.04
-6.
As this function has been called `f', we will create the file f.m using the Matlab editor. To open the editor press the new file icon (the left icon above the command window). Once in the editor, type the following lines into the file.

                         % As the function is called `f'
                         % put this code in the file `f.m'
function  y  =  f( x ) 
%                      
%                                % These are
%  This  is the  test function.  % comments.
%  from section 9.              
%
   term1   =  1 ./( (x-.3).^2 + .01 )  ;
   term2   =  1 ./( (x-.9).^2 + .04 ) ;
   y = term1 + term2 - 6  ;
 

After the lines have been typed in, save the file (by pressing the disk icon). You will be asked for a name; in this case use f.m. Then return to the command window.

If the code has been typed into the file correctly, we should be able to use f the same way we use standard functions like sin and cos etc. For instance, can evaluate f(.3), f(.9), and plot f.

f(.3)        %  Check the code gives the correct answers
f(.9)        %      at   two test points.
 
x = (-1 : .05 : 2)';       % Plot  f  between  -1  and  2 .
plot( x , f(x) ) ;

To guard against errors in the code we should check the answers. Pencil and paper shows  
f(.3) = 1
02+.01
+ 1
(-.6)2+.04
-6 = 100+ 1
.4
-6 = 96.5 ;
and similarly f(.9) = 21.7027. The Matlab answers should be the same. If these commands do not work or give wrong answers, there is probably a typing error. If so, go back into the file and correct the error. Save the file then try to use the function in Matlab again.

Sometimes Matlab does not notice the changes to the code and continues to report errors after we have corrected them. This is usually because we have forgotten to save the file to disk. Annother common cause is that we are editing a file in one directory and Matlab is reading the file in another directory. But occasionally this is due to a Matlab installation bug. To correct this bug, after changing code give the command

clear functions

9.2  Notes on Functions

9.2.1  Code is private

Let us look at the structure of `f.m'.

  1. The first line (apart from comments) is the header. It declares that the value of x comes from the main Matlab program (it is the input argument).

  2. The value of y is calculated by the code in `f.m' and returned to the main program (it is the output argument).

  3. The code in the `f.m' is kept separate from the main Matlab command window, so that term1 in the code for f is different to a variable term1 used in the main program. More pessimistically, the function does not know the value of a variable in the main program unless it is one of the input arguments.

9.2.2  Use . operators

It is best to use the component-wise operators in the code. (We used ./ rather than / for example.) This allows Matlab to correctly evaluate f(x), even when x is a vector. Otherwise plot commands will not work for our function.

9.2.3  Other editors

It is possible to use your favourite editor not just the inbuilt Matlab editor. To use the windows notepad editor use the command

       !notepad f.m &      %  Call the ''Notepad'' editor
                           %     to edit the file  f.m .
                           %  Remember the  &  at the end.

(If you do not remember the `&' at the end of this command, Matlab will refuse to run until you quit notepad.)

Exercise 27

Write an M-file to code the function
g(x) = (1-2x2)exp(-x2).

(a.) Test your function by evaluating it at x = 1 and x = -2.

(b.) Test that your function works correctly when x is a vector by evaluating g for the vector
x = é
ê
ë
1
-2
ù
ú
û
.

(c.) Plot your function for -3 £ x £ 3 using both fplot and the plot command.

We will now use our function f(x) to demonstrate minimization, zero finding, and numerical integration in Matlab.