Accelerating the pace of engineering and science

• Trials

# function

Declare function name, inputs, and outputs

## Syntax

• function [y1,...,yN] = myfun(x1,...,xM) example

## Description

example

function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first executable line of the function.

Save the function code in a text file with a .m extension. The name of the file should match the name of the first function in the file. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

You can declare multiple local functions within the same file, or nest functions. If any function in a file contains a nested function, all functions in the file must use the end keyword to indicate the end of the function. Otherwise, the end keyword is optional.

## Examples

expand all

### Function with One Output

Define a function in a file named average.m that accepts an input vector, calculates the average of the values, and returns a single result.

```function y = average(x)
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
end```

Call the function from the command line.

```z = 1:99;
average(z)```
```ans =
50```

### Function with Multiple Outputs

Define a function in a file named stat.m that returns the mean and standard deviation of an input vector.

```function [m,s] = stat(x)
n = length(x);
m = sum(x)/n;
s = sqrt(sum((x-m).^2/n));
end```

Call the function from the command line.

```values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat(values)```
```ave =
47.3400
stdev =
29.4124```

### Multiple Functions in a File

Define two functions in a file named stat2.m, where the first function calls the second.

```function [m,s] = stat2(x)
n = length(x);
m = avg(x,n);
s = sqrt(sum((x-m).^2/n));
end

function m = avg(x,n)
m = sum(x)/n;
end```

Function avg is a local function. Local functions are only available to other functions within the same file.

Call function stat2 from the command line.

```values = [12.7, 45.4, 98.9, 26.6, 53.1];
[ave,stdev] = stat2(values)```
```ave =
47.3400
stdev =
29.4124```