Extras: 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 variab. 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 following 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 following line.


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 the following code 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 type help function or doc function at the MATLAB command line for more information.

Functions created for this set of tutorials