MATLAB:User-defined Function

From PrattWiki
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, 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);

nargin and nargout

When a function is called, two different values will exist in the function universe: nargin and nargout. These will report back how many input arguments were given when the function was called and how many output arguments were asked for. Image a function ArgCountDemo

function [ o1, o2, o3 ] = ArgCountDemo( i1, i2, i3 )
%% Counts the number of input arguments to the function for a given call
n_in = nargin
%% Counts the number of output arguments requests from the function for a given call
n_out = nargout
%% Put this in just so function has something to return...
o1=0; o2=0; o3=0;

If you run the following script:

echo on
ArgCountDemo;
ArgCountDemo([1 2 3]);
x = ArgCountDemo([1 2 3]);
[x, y] = ArgCountDemo([1 2 3], [4 5]);
[x, y, z] = ArgCountDemo([1 2 3], [4 5], [6 8; 7 9]);
echo off

you will get the following output (with extra linebreaks removed):

ArgCountDemo;
n_in =
     0
n_out =
     0
ArgCountDemo([1 2 3]);
n_in =
     1
n_out =
     0
x = ArgCountDemo([1 2 3]);
n_in =
     1
n_out =
     1
[x, y] = ArgCountDemo([1 2 3], [4 5]);
n_in =
     2
n_out =
     2
[x, y, z] = ArgCountDemo([1 2 3], [4 5], [6 8; 7 9]);
n_in =
     3
n_out =
     3
echo off

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."

Miscellaneous

I/O Requirements

MATLAB functions do not actually have to have inputs or outputs. Sometimes, functions will be written that neither accept values nor provide them. The main reason to do this is to completely isolate the function from the workspace without having to clear the workspace.

Naming and Calling Functions

For functions, MATLAB will know to look for the function by its filename and not by the FNAME in the function paradigm. For example, if the code

function out = NotMyRealName(in)
x = in * 3;
y = x/2;
out = x+y;

existed in a file called RunMe.m, MATLAB would assume that the function is the RunMe function and so

z = RunMe(2)

would work and MATLAB would respond:

z =

     9

while the code

z = NotMyRealName(2)

would give an error

??? Undefined function or method 'NotMyRealName' for input arguments of type 'double'.

Naming and Calling Subfunctions

Subfunctions are subordinate functions that are defined within the text of a function file. Subfunctions are only seen by the function in which they are contained, and for that reason, they are actually called by the FNAME in the subfunction definition. For example, in the code SomeSubs.m below

function out = blah(in)
x = HalfMe(in);
y = SquareMe(x);
out = y;
end

function alpha = HalfMe(beta)
alpha = beta / 2;
end

function gamma = SquareMe(delta)
gamma = delta.^2;
end

the code would be run in the workspace by writing, for example,

SomeSubs(1:4)

and the result would be

ans =

    0.2500    1.0000    2.2500    4.0000

However, you could not write

HalfMe(1)

in the workspace because there is no HalfMe.m - only the SomeSubs.m function can see it.

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