Introduction to Matlab |
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.
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
|
% 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
|
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
Let us look at the structure of `f.m'.
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.
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.)
|
(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
|
(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.