M. Nelson Spring 2004

New Matlab Commands

No new commands this week!

New Matlab Techniques

Functions New functions can be added to MATLAB by creating a file with an extension of '.m', whose name defines the name of the new function. At the top of the file must be a line that contains the syntax definition for the new function. For example, to create a new function stats(x) that returns the mean and standard deviation of the elements in vector x, you need to create a file call stats.m with the following lines: function [mean,stdev] = stats(x) %STATS returns mean and standard deviation of x n = length(x); mean = sum(x) / n; stdev = sqrt(sum((x - mean).^2)/n); Then you could use this function from the command line, or in your scripts. For example, >> z = randn(100,1); >> [zmean, zstd] = stats(z); The variables within the body of the function are local variables. Functions do not have access to workspace variables, except for those that are explicitly passed as inputs and outputs of the function (or those defined as global variables; type 'help global' for more info). Functions must be placed in a directory that is in the Matlab search path (type 'help path' for more info.) The current working directory is in the Matlab search path. Functions normally return when the end of the file is reached. You do not need an end statement at the end of the file. A return statement can be used to force an early return (for example, if an error is detected). Subfunctions A subfunction that is visible to the other functions in the same file is created by defining a new function with the function keyword after the body of the preceding function or subfunction. For example, we could define avg as a subfunction within the file stats.m as follows: function [mean,stdev] = stats(x) %STATS returns mean and standard deviation of x n = length(x); mean = avg(x,n); stdev = sqrt(sum((x - mean).^2)/n); function mean = avg(x,n) %MEAN subfunction mean = sum(x)/n; Subfunctions are not visible outside the file where they are defined. Subfunctions can only be included in a function file (i.e., a file that begins with a function definition); they cannot be included in a regular Matlab script file. |