matlab /mit/2.670/Computers/Matlab/Examplesstarts up matlab and adds that directory to the places matlab will look for .m files in.)
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)./arg1then 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.
narginused within a function tells you how many arguments the function was called with.
You can write functions that can accept different numbers of arguments and decide what to do based on whether it gets two arguments or three arguments, for example.
evallets you take a string and run it as a matlab command.
For example, if I have to plot 20 similar data files for trials and I want to load each file and use the filename in the title, I can write a function that takes the filename as a string as an argument. To load it in the function, I can use
str = ['load ' filename]
to put together a command string, and
eval(str)
to run that command.
Then to use the filename in the title, I can use
str = ['title(' filename ')']
eval(str)
fevalevaluates a function for a given set of arguments. For example, feval('sin',[0:pi/4:2*pi]) is the same thing as saying sin([0:pi/4:2*pi]). If you're dealing with a situation where you might want to specify which function to use as an argument to another function, you might use feval.