# Writing your own functions

If you put any valid sequence of Matlab statements into a file and
give the
file a name ending with the suffix *.m*, then
Matlab will execute those statements if you type the name of the file
(without the suffix). You can use any text editor to create the file.
Matlab's `edit` command will try to use Matlab's own editor,
which has a built-in debugger.

For example, if you have a file called *dothis.m*
which contains the text

back = [] for k=10:-1:1, back=[back,k], end

then just typing `dothis` will cause the `for` loop to be executed.
Such files are called *script* files.

If the first line of such a file has the form

function outputs = somename(inputs)

then it becomes a *function*. In this case `inputs` and
`outputs` are formal parameters, and variables used inside the file
will be local to that file, which means that they will not clash with
other variables you may have used having the same names (unless these are
explicitly declared to be `global`). (Matlab functions correspond to
subroutines in Fortran or functions in C++.)

In an earlier section we wrote a Matlab statement for
finding the centre of gravity of a set of weights, given their
locations along a straight line. If you wanted to
calculate centres of gravity repeatedly, then you could write a
function which would perform the required calculation, and
store it for future use. All you need to
do is to create a file called *cofg.m* in your directory (using
an editor) which contains the following text:

function cg = cofg(weights, locations) % Comments are introduced by percent signs, as here. % These initial comments will be written to the terminal % if you type 'help cofg'. It is useful to remind the % user how to call the function by putting in the line: % cg = cofg(weights, locations) cg = weights * locations' / sum(weights);

and that's all there is to it! When this file exists in your directory, you can type the following in Matlab:

cg = cofg([3 1 7],[-2 0 5])

Of course it may be advisable to make your function more sophisticated, for example to check whether both input arguments are row vectors, or to make sure that it will work with either row or column vectors. (Note that this function as written here will in fact work in two or three dimensions. Can you see why the following works?

xlocations = [-2 0 5] ylocations = [1 2 3] xylocations = [xlocations ; ylocations] cg2 = cofg([3 1 7], xylocations)

This gives the *x* and *y* coordinates of the centre of gravity.)

To see the whole of your function from within Matlab, type `type cofg`.
Try this with some other functions, such as `type angle` or
`type gradient`.

It is also possible to pick up subroutines which have been written in other languages and pre-compiled. See the Interface Guide for details.