Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Global variables Up: Matlab Databook Previous: switch

Writing your own scripts and functions

It soon gets tedious to type everything on the command line. If you put any valid sequence of Matlab statements into a file (using an editor) 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). For example, if you type edit dothis, then matlab will start an editor ready to edit a file called dothis.m. If you save the following text into it
        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).

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 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.

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



 
next up previous contents
Next: Global variables Up: Matlab Databook Previous: switch
© Cambridge University Engineering Dept
Information provided by Tim Love
2006-07-24