# Matlab Functions

## Contents

## Why Functions?

Any time that you find yourself duplicating a section of code with
minor changes, you should consider using a function. As an example,
let's consider the R^{2} value,
commonly used in regression.

where is a predicted value of , is the observed value, and is the average value of the observed value of . We could create a function to calculate the value and then use it rather then repeating the code to calculate each time it is needed.

Perhaps without realizing it, you have used many functions in Matlab. For example, linspace, ones, zeros, etc. are all functions.

## Function Basics

A function has a few basic ingredients:

- Input arguments - these are the arguments that the caller provides to the function. Functions may take 0 to many input arguments.
- Output arguments - these are the result(s) of the function. Functions may provide 0 to many output arguments.
- Documentation! See the tips section for more information on documenting functions.

All variables used within a function can only be "seen" within that function.

### Example

Let's consider an example of calculating the rate constant for a reaction: A function to calculate this might look like:

```
function k = rate_constant( A, Ea, T )
% k = rate_constant( A, Ea, T )
% A - pre-exponential factor, units vary
% Ea - Activation energy, J/mol
R = 8.314; % Gas constant, J/(mol K)
k = A*exp(-Ea/(R*T));
``` |

### Tips for creating functions

- The function name should be the same as the m-file that you save it in. In the above example, the function was called
`rate_constant`and we called the matlab file`rate_constant.m`. - Document your function! At a minimum, provide comments illustrating how to use the function and describing the input and output arguments. Then you can type "help [function]" at the command line to learn how to use it. For example, you could type
`help rate_constant`and the first block of comments would be displayed.

## Anonymous Functions

Occasionally we want to create a function but we don't want to hassle
with creating an m-file. We can use an *anonymous function* to help
here.

Anonymous functions have a few key features:

- They have access to any variables defined above them in the function where they are defined.
- They are not visible outside of the function that they are defined in.

As a simple example, let's assume that we want to plot
for various values of . The following
code does this:

```
clear; clc; close all;
% create an anonymous function called "func"
func = @(b,x)(x.^b);
x = linspace(0.1,3,100); % independent values.
fx = zeros(3,100); % array to hold the function values
legendentry = {}; % array to stash legend entries.
for b=1:5
% calculate the function values for this value of b
% and then create the legend entry.
fx(b,:) = func(b,x);
legendentry{b} = strcat('b=',num2str(b));
end
% plot on a log-log scale
loglog(x,fx);
xlabel('x'); ylabel('x^b');
legend(legendentry);
```

Of course, in this case it would have been just as easy to do this without a function, but this illustrates how to use an anonymous function.

## Practical Uses of Functions

Functions are regularly used when solving nonlinear equations, performing numerical integration, and solving ordinary differential equations in Matlab.