Programming and Data Types |

**Functions**

Functions are M-files that accept input arguments and return output arguments. They operate on variables within their own workspace. This is separate from the workspace you access at the MATLAB command prompt.

This section covers the following topics regarding functions:

- Simple Function Example
- Basic Parts of a Function M-File
- How Functions Work
- Checking the Number of Function Arguments
- Passing Variable Numbers of Arguments

**Simple Function Example**

The `average`

function is a simple M-file that calculates the average of the elements in a vector.

function y = average(x) % AVERAGE Mean of vector elements. % AVERAGE(X), where X is a vector, is the mean of vector elements. % Nonvector input results in an error. [m,n] = size(x); if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) error('Input must be a vector') end y = sum(x)/length(x); % Actual computation

If you would like, try entering these commands in an M-file called `average.m`

. The `average`

function accepts a single input argument and returns a single output argument. To call the `average`

function, enter

Scripts | Basic Parts of a Function M-File |