MATLAB(TM) Hypertext Reference, Copyright (c) 1995 Gerald Recktenwald, All rights reserved

MATLAB Functions -- Basic Features






Functions versus Scripts

See Scripts versus Functions.




Anatomy of a MATLAB function

MATLAB functions are similar to C functions or Fortran subroutines.

MATLAB programs are stored as plain text in files having names that end with the extension ``.m''. These files are called, not surprisingly, m-files. Each m-file contains exactly one MATLAB function. Thus, a collection of MATLAB functions can lead to a large number of relatively small files.

One nifty difference between MATLAB and traditional high level languages is that MATLAB functions can be used interactively. In addition to providing the obvious support for interactive calculation, it also is a very convenient way to debug functions that are part of a bigger project.

MATLAB functions have two parameter lists, one for input and one for output. This supports one of the cardinal rules of MATLAB programming: don't change the input parameters of a function. Like all cardinal rules, this one is broken at times. My free advice, however, is to stick to the rule. This will require you to make some slight adjustments in the way you program. In the end this shift will help you write better MATLAB code.

Creating function m-files with a plain text editor

MATLAB m-files must be plain text files, i.e. files with none of the special formatting characters included by default in files created by word-processors. Most word-processors provide the option of saving the file as plain text, (look for a ``Save As...'' option in the file menu). A word-processor is overkill for creating m-files, however, and it is usually more convenient to use a simple text editor, or a ``programmer's editor''. For most types of computers there are several text editors (often as freeware or shareware). Usually one plain text editor is included with the operating system.

When you are writing m-files you will usually want to have the text editor and MATLAB open at the same time. Since modern word-processors require lots of system RAM it may not even be possible or practical (if you are working on a stand-alone personal computer) for you to use a word-processor for m-file development. In this case a simple, text editor will be your only option.

Function Defintion

The first line of a function m-file must be of the following form.
    function [output_parameter_list] = function_name(input_parameter_list)
The first word must always be ``function''. Following that, the (optional) output parameters are enclosed in square brackets [ ]. If the function has no output_parameter_list the square brackets and the equal sign are also omitted. The function_name is a character string that will be used to call the function. The function_name must also be the same as the file name (without the ``.m'') in which the function is stored. In other words the MATLAB function, ``foo'', must be stored in the file, ``foo.m''. Following the file name is the (optional) input_parameter_list.

There can exactly be one MATLAB function per m-file.

Input and Output parameters

The input_parameter_list and output_parameter_list are comma-separated lists of MATLAB variables.

Unlike other languages, the variables in the input_parameter_list should never be altered by the statements inside the function. Expert MATLAB programmers have ways and reasons for violating that principle, but it is good practice to consider the input variables to be constants that cannot be changed. The separation of input and output variables helps to reinforce this principle.

The input and output variables can be scalars, vectors, matrices, and strings. In fact, MATLAB does not really distinguish between variables types until some calculation or operation involving the variables is performed. It is perfectly acceptable that the input to a function is a scalar during one call and a vector during another call.

To make the preceding point more concrete, consider the following statement

	>> y = sin(x)
which is a call to the built-in sine function. If x is a scalar (i.e. a matrix with one row and one column) then y will be a scalar. If x is a row vector, then y will be a row vector. If x is a matrix then y is a matrix. (You should verify these statements with some simple MATLAB calculations.)

This situation-dependence of input and output variables is a very powerful and potentially very confusing feature of MATLAB. Refer to the ``addtwo.m'' function below for an example.

Comment statements

MATLAB comment statements begin with the percent character, %. All characters from the % to the end of the line are treated as a comment. The % character does not need to be in column 1.


Some simple examples

Here is a trivial function, addtwo.m
	function addtwo(x,y)
	%  addtwo(x,y)  Adds two numbers, vectors, whatever, and
	%               print the result = x + y
	x+y
The addtwo function has no output parameters so the square brackets and the equal sign are omitted. There is only one MATLAB statement, x+y, in the function. Since this line does not end with a semicolon the results of the calculation are printed to the command window.

The first two lines after the function definition are comment statements. Not only do these statements describe the statements in the file, their position in the file supports the on-line help facility in MATLAB. If the first line of a MATLAB function definition is immediately followed by non-blank comment statements, then those comment statements are printed to the command window when you type ``help function_name". Try it with the addtwo function. MATLAB will print up until a blank line or an executable statement, whichever comes first. Refer to the Function prologues -- providing help section for more information.

To test your understanding of input and output variables, pass the following definitions of x and y to the addtwo function. (To save space the x and y variables are defined on the same line. You can enter these variables on the same line, as shown, or use separate lines.)

	>> x = 2;         y = 3;
	>> x = [2 3];     y = [4; 5];
	>> x = eye(3,3);  y = -2*eye(3,3);
	>> x = 'Sue';     y = 'Bob'
	>> x = 'Jane';    y = 'Bob'

Here is another simple function, traparea.m, with three input parameters and one output parameter. Since there is only one output parameter the square brackets may be omitted.

	function area = traparea(a,b,h)
	%  traparea(a,b,h)   Computes the area of a trapezoid given
	%                    the dimensions a, b and h, where a and b
	%                    are the lengths of the parallel sides and
	%                    h is the distance between these sides
	
	%  Compute the area, but suppress printing of the result
	area = 0.5*(a+b)*h;
Note that there is a blank line between the comment statements that describe the function and the single comment statement that describes the calculation of area. The comment statement beginning ``Compute the area...'' will not be printed if you type ``help traparea''. Also note that there is no ``return'' statement needed. (There is a MATLAB return statement, but it is not needed here.) The output variable, area, is defined in the first line of the file. The value assigned to area is returned to the calling function or the command window.

Finally, here is another simple function, cart2plr.m, with two input parameters and two output parameters.

	function [r,theta] = cart2plr(x,y)
	%   cart2plr  Convert Cartesian coordinates to polar coordinates
	%
	%   [r,theta] = cart2plr(x,y) computes r and theta with
	%
	%       r = sqrt(x^2 + y^2);
	%       theta = atan2(y,x);
	
	r = sqrt(x^2 + y^2);
	theta = atan2(y,x);
The comment statements have empty lines, but these will be printed if you type ``help cart2plr''.


Make sure MATLAB knows the path to your function

MATLAB cannot execute a function unless it knows where to find its m-file. This requires that the function be in the internal MATLAB path. Refer to ``Setting the MATLAB Path'' for more information.


Calling MATLAB Functions




Local Variables

Unless explicitly declared to be global variables, all variables appearing in a MATLAB function are local to that function.




Flow Control

MATLAB supports the basic flow control constructs found in most high level programming languages. The syntax is a hybrid of C and Fortran and I often create polyglot statements which lead to the joyless task of squashing trivial bugs.

if constructs

MATLAB supports these variants of the ``if'' construct Here are some examples based on the familiar quadratic formula. (n.b. This is not an endorsement of the code logic, just an easy to follow example of the ``if'' constructs.)

A simple warning

	>> d = b^2 - 4*a*c;
	>> if d<0
	>>   disp('warning: discriminant is negative, roots are imaginary');
	>> end
or a warning plus extra notification
	>> d = b^2 - 4*a*c;
	>> if d<0
	>>   disp('warning: discriminant is negative, roots are imaginary');
	>> else
	>>   disp('OK: roots are real, but may be repeated');
	>> end
or, no secrets whatsoever
	>> d = b^2 - 4*a*c;
	>> if d<0
	>>   disp('warning: discriminant is negative, roots are imaginary');
	>> elseif d==0
	>>   disp('discriminant is zero, roots are repeated');
	>> else
	>>   disp('OK: roots are real and distinct');
	>> end
Careful inspection of the preceding statements reveals that Indentation of ``if'' blocks is not required, but considered good style.

The compact if

If you read tightly coded m-files (e.g., many of the built-in MATLAB functions) you will discover a variant of the if ... end construct that is written on one line. Here's an example
	if x<0, disp('imaginary'); end
Notice the comma between the x<0 and the disp(...). Apparently the comma tells the MATLAB interpretter that the conditional test has ended. To my knowledge this is only place where a statement (OK, part of a statement) ends with a comma. It's just one of those quirks that true believers come to use without hesitation.

Logical comparisons

Table of logical comparison operators

The preceding table lists the logical comparison operators used in MATLAB. Note that these operators can be used in assignment statements, as illustrated in this example

	enough = xnew-xold < delta
	if ~enough
	   stepSize = stepSize/2;
	end
The first statement assigns the value of the logical comparison to the variable ``enough''. If the comparison on the right hand side evaluates to be true, then enough is given the value 1. If the comparison evaluates to be false, then enough is given the value 0. In the subsequent if statement, enough = 1 is true, and enough = 0 is false.

Binary and unary logical operators

Binary operators take two arguments (operands). Unary operators take one argument.

The && operator (read ``and'' operator) takes two logical expressions and returns ``true'' if both expressions are true, and ``false'' otherwise.

The || operator (read ``or'' operator) takes two logical expressions and returns ``true'' if either of the expressions are true, and ``false'' only if both expressions are false. The possible outcomes of && and || operations are summarized in the following truth table.

Truth table for && and ||

The ~ operator (read ``not'') takes only one logical expression and returns the opposite (negation) of that expression. Consider the following code

	a = 2;  b = 3;
	asmall = a < b;     %   asmall is ``true''
	if ~asmall
	  disp('a is greater than b')
	end
Since a is less than b the if ~asmall block is not executed because ~asmall is false.

while constructs

The syntax of the while construct is
	while expression
	   do something
	end
where ``expression'' is a logical expression. The ``do something'' block of code is repeated until the expression in the while statement becomes false.

Here is an example

	i = 2;
	while i<8
	  i = i + 2
	end
Executing the preceding block of code results in the following output to the command window
	i = 4
	i = 6
	i = 8
(The output has been adjusted to take up less space. MATLAB likes to sprawl its printout over several lines.) Note that no disp or fprintf statement was needed in the preceding block because the i = i + 2 statement did not end in a semicolon.

for constructs

The for construct is used to create a loop, usually over a fixed range of steps
	sum = 0;
	for i=1:length(x)
	while i<10
	   sum = sum + abs(x(i));
	end





[Preceding Section] [Master Outline] [Section Outline] [Next Section]