Functions extend the concept of script in two ways:

  1. they can be passed (and return) an arbitrary number of arguments, depending only on the function syntax
  2. by default, variables defined in functions are local variables; they cannot be accessed outside of the function and are completely unavailable after the function call completes (hence necessitating the passing of variables to and from the function).

Functions may also be passed the special variable varargin (also see this page) and return a similar special variable varargout.

File: funcHello.m

function funcHello(s)
disp(s);
Calling the funcHello function

>> funcHello('Hi There!');
Hi There!

funcHello can be called, as shown above, as long as it is found in MATLAB's path; this can be changed by using addpath, or simply by changing the current directory within the MATLAB interpreter using the cd command.

Functions are similar to scripts in that they are defined as a text file with a '.m' extension and are called from the interpreter (or from other functions/scripts) using the same name (without the '.m' extension). For a function that returns no arguments, the syntax consists of the word 'function' in the first line of the file, followed by the name of the function, an opening parenthesis, a comma-separated list of input variable names, and finally, a closing parenthesis.

It is not required, but most programmers indent the body of their functions by two spaces or more to set them off from the function header and to differentiate them from scripts. This function example simply prints a string which is passed to the function using the previously-discussed built-in 'disp' function. Note that the type of the input variable 's' is not specified -- MATLAB is a weakly-typed language and a function will try to operate on any data type which is passed to it. The 'disp' function, for example, will print almost any type of variable passed to it, including scalars, vectors and strings.

 
©   Cornell University  |  Center for Advanced Computing  |  Copyright Statement  |  Inclusivity Statement