Writing Functions and Scripts

All matlab functions and scripts are plain text files that contain matlab commands. Matlab will treat any file that ends in .m as either a function or a script. It can find .m files you've written that are in your ~/matlab directory, in the directory you have cd'd into from the matlab prompt, or in a directory you've started matlab with (ie,
 matlab /mit/2.670/Computers/Matlab/Examples
starts up matlab and adds that directory to the places matlab will look for .m files in.)


A script is just a list of commands to be run in some order. Placing these commands in a file that ends in .m allows you to "run" the script by typing its name at the command line. You type the name of the script without the .m at the end.


A function is capable of taking particular variables (called arguments) and doing something specific to "return" some particular type of result. A function needs to start with the line

function return-values = functionname(arguments)

so that matlab will recognize it as a function. Each function needs to have its own file, and the file has to have the same name as the function. If the first line of the function is

function answer = myfun(arg1,arg2)
answer = (arg1+arg2)./arg1
then the file must be named myfun.m. The function has arg1 and arg2 to work with inside the function (plus anything else you want to define inside it, and possibly some global variables as well), and by the end of the function, anything that is supposed to be returned should have a value assigned to it. This particular function is just one line long, and it returns answer, which is defined in terms of the two arguments arg1 and arg2.

Some useful tools for functions and scripts