User defined functions

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

`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

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
is an array, then becomes an array of function values. - The semicolon at the end prevents that at every function evaluation unnecessary output appears on your screen.

You can change the definition of

`edit f`

in the command prompt.
Sometimes it is more convenient to define your function at the command line. MATLAB functions produced at the command line are called

>> f = @(x)(x.^2+exp(x))Here,

`@`

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) ans = 4.7601

Esteur 2010-03-22