Difference between revisions of "Matlab Functions"

From Sutherland_wiki
Jump to: navigation, search
m (Anonymous Functions)
 
(3 intermediate revisions by the same user not shown)
Line 3: Line 3:
  
 
== Why Functions? ==
 
== Why Functions? ==
  Provide general description and motivation
+
 
 +
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 [[Regression#The_R2_Value|R<sup>2</sup> value]],
 +
commonly used in [[regression]].
 +
:<math>
 +
  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 },
 +
</math>
 +
where <math>\phi_{i}^{predicted}</math> is a predicted value of
 +
<math>\phi</math>, <math>\phi_i^{observed}</math> is the observed
 +
value, and <math>\bar{\phi}=\frac{1}{n}\sum_{i=1}^n \phi_i^{observed}
 +
</math> is the average value of the observed value of
 +
<math>\phi</math>. We could create a function to calculate the
 +
<math>R^2</math> value and then use it rather then repeating the code
 +
to calculate <math>R^2</math> each time it is needed.
 +
 
 +
Perhaps without realizing it, you have used many functions in Matlab.
 +
For example, [[Matlab_Arrays#Linspace_and_Logspace|linspace]],
 +
[[Matlab_Arrays#Shortcuts_for_Special_Matrices|ones]],
 +
[[Matlab_Arrays#Shortcuts_for_Special_Matrices|zeros]], etc. are all
 +
functions.
 +
 
  
  
 
== Function Basics ==
 
== Function Basics ==
  
=== Arguments ===
+
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_for_creating_functions|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:
 +
<math>k=A \exp \left(\frac{-E_a}{RT}\right)</math>
 +
A function to calculate this might look like:
 +
{| border=3 cellpadding="5" cellspacing="0"
 +
|+ '''rate_constant.m
 +
|-
 +
|<source lang="matlab">
 +
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));
 +
</source>
 +
|}
 +
 
  
=== Variable Scope ===
 
  
 +
=== 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 <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.
  
 
== Anonymous Functions ==
 
== 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
 +
<math>y=x^b</math> for various values of <math>b</math>. The following
 +
code does this:
 +
 +
<source lang="matlab">
 +
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);
 +
</source>
  
== Calling Functions ==
+
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 as Arguments ===
+
Functions are regularly used when
Discuss anonymous functions as well as regular m-file functions.
+
[[Nonlinear_equations#FZERO|solving nonlinear equations]], performing
 +
[[Numerical_Integration|numerical integration]], and solving
 +
[[ODEs|ordinary differential equations]] in Matlab.

Latest revision as of 18:03, 19 February 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.

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));
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.