MATLAB functions are subprograms that contain a sequence of MATLAB commands,
and that are stored in separate m-files. An m-file is a plain text file with
the file extension .m
.
-
Functions exchange data via lists of input and output variables.
-
Functions can call other functions.
-
A very large fraction of built-in \MATLAB\ commands are functions. For example, enter
type mean
at the command prompt.
Basic structure of a MATLAB Function
The schematic above represents the basic components of an m-file function.
-
The name of the function is
myFun
and it is stored in a an m-file calledmyFun.m
. -
The first line is the function definition line, which must begin with the word
function
. -
Output variables appear after the
function
keyword and before the equals sign. Output variables are enclosed in square brackets.[r, s, t, . . .]
. -
Input variables appear after the name of the function. The input variables are enclosed in parenthesis.
(a, b, c, . . .)
.
Functions provide structure
Functions perform tasks outside of the command window environment (outside the memory space of the command window). In other words, variables defined and used inside a function are not connected to variables defined and used in the command window or in other functions, except when the values of those variables are passed into the function as input variables, or out of the function as output variables.
It makes sense to define functions to perform a single task or a sequence of very closely related tasks. By creating a modular structure, it is easier to organize a complex calculation into a group of functions, each of which has a narrowly defined tasks. Those individual functions can be developed and debugged separately. Furthermore, once a function is developed and debugged, it is available for reuse in other calculations.