Difference between revisions of "Matlab Functions"

From Sutherland_wiki
Jump to: navigation, search
(First pass at a page describing how to use MATLAB functions.)
m (Function Basics)
Line 33: Line 33:
 
* Input arguments - these are the arguments that the caller provides to the function.  Functions may take 0 to many input arguments.
 
* 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.
 
* Output arguments - these are the result(s) of the function.  Functions may provide 0 to many output arguments.
* Documentation!  See the [[Tips_for_creating_functions]] section for more information on documenting functions.
+
* Documentation!  See the [[#Tips_for_creating_functions|tips]] section for more information on documenting functions.
  
 
All variables used within a function can only be "seen" within that function.
 
All variables used within a function can only be "seen" within that function.
Line 62: Line 62:
 
# The function name should be the same as the m-file that you save it in. In the above example, the function was called <tt>rate_constant</tt> and we called the matlab file <tt>rate_constant.m</tt>.
 
# The function name should be the same as the m-file that you save it in. In the above example, the function was called <tt>rate_constant</tt> and we called the matlab file <tt>rate_constant.m</tt>.
 
# 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 <tt>help rate_constant</tt> and the first block of comments would be displayed.
 
# 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 <tt>help rate_constant</tt> and the first block of comments would be displayed.
 
  
 
== Anonymous Functions ==
 
== Anonymous Functions ==

Revision as of 17:20, 26 January 2009


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.


Example

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:

rate_constant.m
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. For 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));
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.