Eng.Saeed Almalowi
Posts : 38 Join date : 2009-10-27 Location : UNITED STATE OF AMERICA, STATE COLLEGE,PA
| Subject: WRITING FUNCTIONS AND SCRIPTS Thu Oct 29, 2009 6:52 am | |
| 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.)
Scripts 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.
Functions 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
*
nargin
used 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.
*
eval
lets 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)
*
feval
evaluates 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. | |
|