Difference between revisions of "MATLAB:User-defined Function"

From PrattWiki
Jump to navigation Jump to search
Line 15: Line 15:
 
create a function <code>c</code> by creating a file called <code>c.m</code> in the current working directory as follows:   
 
create a function <code>c</code> by creating a file called <code>c.m</code> in the current working directory as follows:   
 
<source lang="matlab">
 
<source lang="matlab">
function out=c(a, b)
+
function out=c(a, b, theta)
 
out = sqrt(a.^2+b.^2-2*a.*b.*cos(theta));
 
out = sqrt(a.^2+b.^2-2*a.*b.*cos(theta));
 
</source>
 
</source>
Line 77: Line 77:
 
</source>
 
</source>
  
 +
==Comments in User-defined Functions and Function Help Files==
 +
Comments are allowed in user-defined functions just as they would be in scripts - all you need to do is put the % symbol before the line you want to make a comment.  The main difference in functions versus scripts is that you can actually set up some of the comments to act as the local help file for the function.  Whatever comments are directly below the <code>function</code> line are considered the help file.  The "help file" ends with the first uncommented line, whether it is a blank space or a line of uncommenteed code.  For example, assume the file <code>inTOm.m</code> contains the following text:
 +
<source lang="matlab">
 +
function MetersOut = inTOm(InchesIn)
 +
% inTOm  Convert a measurement in inches to one in meters
 +
%
 +
% Synopsis: MetersOut = inTOm(InchesIn)
 +
%
 +
% Input:  InchesIn = measurement in inches
 +
% Output: MetersOut = measurement in meters
 +
 +
% Multiply by 2.54 to get centimeters, then
 +
% divide by 100 to get meters
 +
MetersOut = InchesIn * 2.54 / 100;
 +
</source>
 +
If you type <code>help inTOm</code> in the command window, MATLAB will respond with:
 +
<source lang="text">
 +
  inTOm  Convert a measurement in inches to one in meters
 +
 +
  Synopsis: MetersOut = inTOm(InchesIn)
 +
 +
  Input:  InchesIn = measurement in inches
 +
  Output: MetersOut = measurement in meters
 +
</source>
 +
which is the text in the set of comments just below the <code>function</code> line but stopping at the blank line.  The comments following the blank line are not considered a part of the "help file."
  
 
==MATLAB Help File==
 
==MATLAB Help File==

Revision as of 00:49, 5 September 2008

MATLAB has a feature that lets you create a user-defined function inside a text file. The file itself will determine how many inputs the function can accept, what they are called locally, how many outputs can be returned, and what they are called locally. The name of the function - that is, how to call it in MATLAB - is determined by the name of the file containing the function.

This method is good for functions of any complexity, since the file can contain a multitude of expressions, create local variables, and return as many variables as specified in the file. It is therefore in many ways quite different from creating either an MATLAB:Inline Function or an MATLAB:Anonymous Function.

Syntax

To create a function, you will write a text file with the following format:

function [OUT1, OUT2, ...] = FNAME(IN1, IN2, ...)
        BODY OF FUNCTION

where OUTn are the output variables and INn are the input variables. Somewhere in the body of the function, the values of the output variables should be set. Note that these functions can have any number of inputs - including none - as well as any number of outputs - also including none. For example, if you want \(c(a,b,\theta)\), to return \(\sqrt{a^2+b^2-2ab\cos(\theta)}\), you could create a function c by creating a file called c.m in the current working directory as follows:

function out=c(a, b, theta)
out = sqrt(a.^2+b.^2-2*a.*b.*cos(theta));

You can now use the function by putting numbers in for the arguments - for example:

SideThree = c(2, 3, pi/6)

will return

SideThree =
    1.6148

Note the semi-colon after the second line in the code. While this is not explicitly required, it will keep the function file from reporting the result of that line of code. Most likely, the user does not want to see each execution result inside the function file, so most lines of a function file will end with the semi-colon.

You can also use that function to return entire matrices. For example, the commands:

[x,y] = meshgrid(0:.1:2, 0:.1:2);
mesh(x, y, c(x, y, pi/4));
xlabel('Side 1');
ylabel('Side 2');
zlabel('Side 3');
title('Triangle Third Side vs. Sides Surrounding a 45^o Angle (mrg)')
print -depsc ExamplePlot

will produce the graph:

InlineExamplePlot.png

Multiple Outputs

Note that the name of the output variable in the function file - in this case, out is not the same as the name of the function itself. This is because these functions are capable of returning more than one variable. For example, a function that returns the values of the unit step, ramp, and quadratic given an input of one or more times might be in a file called URQfun.m, which contains:

function [USout, URout, UQout] = URQ(TimeIn)
        USout = (TimeIn>=0);
        URout = TimeIn .* USout;
        UQout = (TimeIn.^2) / 2 .* USout;

You can now use this function to generate the unit step, ramp, and quadratic for times from -1 to 2 with 100 points using the following commands:

%% create a vector with 100 values evenly spaced between -1 and 2
t = linspace(-1, 2, 100); 
%% create vectors u, r, and q which will hold the unit step, ramp, and quadratic
[u, r, q] = URQfun(t);

Making a user-defined function is especially good for 1) functions you use often and 2) functions that are too complicated to put in on one line. Note that you do not have to have to receive all the outputs every time. Using the URQfun function above, the code below will calculate the unit step, ramp, and quadratic but will only store the unit step and unit ramp because MATLAB has only asked for two outputs; the third output matrix passed from the function is lost:

%% create a vector with 100 values evenly spaced between -1 and 2
t = linspace(-1, 2, 100); 
%% create vectors u and r which will hold the unit step and ramp
[u, r] = URQfun(t);

Comments in User-defined Functions and Function Help Files

Comments are allowed in user-defined functions just as they would be in scripts - all you need to do is put the % symbol before the line you want to make a comment. The main difference in functions versus scripts is that you can actually set up some of the comments to act as the local help file for the function. Whatever comments are directly below the function line are considered the help file. The "help file" ends with the first uncommented line, whether it is a blank space or a line of uncommenteed code. For example, assume the file inTOm.m contains the following text:

function MetersOut = inTOm(InchesIn)
% inTOm  Convert a measurement in inches to one in meters
%
% Synopsis: MetersOut = inTOm(InchesIn)
%
% Input:  InchesIn = measurement in inches
% Output: MetersOut = measurement in meters

% Multiply by 2.54 to get centimeters, then
% divide by 100 to get meters
MetersOut = InchesIn * 2.54 / 100;

If you type help inTOm in the command window, MATLAB will respond with:

  inTOm  Convert a measurement in inches to one in meters
 
  Synopsis: MetersOut = inTOm(InchesIn)
 
  Input:  InchesIn = measurement in inches
  Output: MetersOut = measurement in meters

which is the text in the set of comments just below the function line but stopping at the blank line. The comments following the blank line are not considered a part of the "help file."

MATLAB Help File

Part of the MATLAB help file for user-defined functions is[1]

 FUNCTION Add new function.
    New functions may be added to MATLAB's vocabulary if they
    are expressed in terms of other existing functions. The 
    commands and functions that comprise the new function must
    be put in a file whose name defines the name of the new 
    function, with a filename extension of '.m'. At the top of
    the file must be a line that contains the syntax definition
    for the new function. For example, the existence of a file 
    on disk called STAT.M with:
  
            function [mean,stdev] = stat(x)
            %STAT Interesting statistics.
            n = length(x);
            mean = sum(x) / n;
            stdev = sqrt(sum((x - mean).^2)/n);
  
    defines a new function called STAT that calculates the 
    mean and standard deviation of a vector. The variables
    within the body of the function are all local variables.
    See SCRIPT for procedures that work globally on the work-
    space.

Notes

  • Functions can have subfunctions defined with in them. Subfunctions cannot be seen by the workspace and may only be accessed by the function and subfunctions included in the file. While functions are called by their filename, subfunctions are called by the FNAME in the subfunction header.

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References

  1. Quoted from MATLAB help file for function