CMU
UM


Introduction to Matlab Functions

When entering a command such as roots, plot, or step into matlab what you are really doing is running an m-file with inputs and outputs that has been written to accomplish a specific task. These types of m-files are similar to subroutines in programming languages in that they have inputs (parameters which are passed to the m-file), outputs (values which are returned from the m-file), and a body of commands which can contain local variables. Matlab calls these m-files functions. You can write your own functions using the function command.

The new function must be given a filename with a '.m' extension. This file should be saved in the same directory as the Matlab software, or in a directory which is contained in Matlab's search path. The first line of the file should contain the syntax for this function in the form:

function [output1,output2] = filename(input1,input2,input3)
A function can input or output as many variables as are needed. The next few lines contain the text that will appear when the help filename command is evoked. These lines are optional, but must be entered using % in front of each line in the same way that you include comments in an ordinary m-file. Finally, below the help text, the actual text of the function with all of the commands is included. One suggestion would be to start with the line:

error(nargchk(x,y,nargin));

The x and y represent the smallest and largest number of inputs that can be accepted by the function; if more or less inputs are entered, an error is triggered.

Functions can be rather tricky to write, and practice will be necessary to successfully write one that will achieve the desired goal. Below is a simple example of what the function, add.m, might look like.

function [var3] = add(var1,var2)
%add is a function that adds two numbers
var3 = var1+var2;

If you save these three lines in a file called "add.m" in the Matlab directory, then you can use it by typing at the command line:

y = add(3,8)
Obviously, most functions will be more complex than the one demonstrated here. This example just shows what the basic form looks like. Look at the functions created for this tutorial listed below, or at the functions in the toolbox folder in the Matlab software, for more sophisticated examples, or try help function for more information.


Functions Created for this Set of Tutorials

jgrid.m | lnyquist1.m | nyquist1.m | polyadd.m | rscale.m | sigrid.m | wbw.m

Tutorials
Basics | Modeling | PID | Root Locus | Frequency Response | State Space | Digital Control | Examples

8/28/96 JDP