|
|||
Department of Engineering | |
University of Cambridge > Engineering Department > computing help |
back = [] for k=10:-1:1, back=[back,k], endthen 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.
| computing help | |