User defined functions

Function m-files
In MATLAB you can also define your own functions. MATLAB assumes by default that all functions act on arrays. Therefore, you must keep in mind the rules for array operations when writing your own functions. You can then combine your own functions with MATLAB functions. A function definition has to be saved in a 'function file', which is a file with the extension `.m'. The name of the file has to be the same as the name of the function, and should have the extension `.m'.

Consider the function $ f(x)=x^2+e^x$ . In MATLAB we will write a function with the same name. The definition of the function has to be saved in the file `f.m'. Through the menu `File $ \backslash$ New $ \backslash$ M-file' or by typing edit on the command line, the `MATLAB Editor/Debugger' is opened. If you now type the lines:
function y = f(x)
y = x.^2 + exp(x);
and you save the file under the name `f.m', then within MATLAB the function $ f(x)$ is available.

Some comments on the file above are in order.
  • The first line of the file has to contain the word `function'. The variables used are local; they will not be available in your 'Workspace'.
  • If $ x$ is an array, then $ y$ becomes an array of function values.
  • The semicolon at the end prevents that at every function evaluation unnecessary output appears on your screen.
Always test the functions you have defined yourself!
You can change the definition of $ f(x)$ by typing the command edit f in the command prompt.

Warning: m-files should not be given the name of existing variables or MATLAB functions. Conversely, after you have defined a function yourself, you should not give variables the same name as your function, otherwise the function will not work any more (see Exercise 1.25).

Anonymous functions
Sometimes it is more convenient to define your function at the command line. MATLAB functions produced at the command line are called anonymous functions. For example, consider again the function $ f(x)=x^2+e^x$ . We can create the anonymous function as follows:
>> f = @(x)(x.^2+exp(x))
Here, $ f$ is the name of the function, @ is the function handle, x is the input argument and x.^2+exp(x) is the function.

Anonymous functions can have multiple input arguments. The general structure of anonymous functions is name = @(input arguments) (functions).

The anonymous function will be evaluated in the same way as the function m-files. Thus the value of $ f(1.2)$ will be obtained by the command

>> f(1.2)

ans =


Previous      Next      Up      Contents

Esteur 2010-03-22