Matlab Functions

From Sutherland_wiki
Jump to: navigation, search

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 R2 value, commonly used in regression.

  R^2 = 1 - \frac{\sum_{i=1}^{n} \left( \phi_{i}^{observed} - \phi_i^{predicted} \right)^2}
 {\sum_{i=1}^{n} \left( \phi_i^{observed} - \bar{\phi} \right)^2 },

where \phi_{i}^{predicted} is a predicted value of \phi, \phi_i^{observed} is the observed value, and \bar{\phi}=\frac{1}{n}\sum_{i=1}^n \phi_i^{observed}
is the average value of the observed value of \phi. We could create a function to calculate the R^2 value and then use it rather then repeating the code to calculate R^2 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.


Let's consider an example of calculating the rate constant for a reaction: k=A \exp \left(\frac{-E_a}{RT}\right) 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

  1. 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.
  2. 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 y=x^b for various values of b. 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));
% plot on a log-log scale
xlabel('x'); ylabel('x^b');

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.