MATLAB:User-defined Function

From PrattWiki
Revision as of 23:09, 4 August 2008 by DukeEgr93 (talk | contribs)
Jump to navigation Jump to search

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


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