Calling Functions

www.kxcad.net Home > CAE Software Index > MATLAB Index >


Your Ad Here

What Happens When You Call a Function

When you call a function M-file from either the command line or from within another M-file, MATLAB parses the function into pseudocode and stores it in memory. This prevents MATLAB from having to reparse a function each time you call it during a session. The pseudocode remains in memory until you clear it using the clear function, or until you quit MATLAB.

Clearing Functions from Memory

You can use clear in any of the following ways to remove functions from the MATLAB workspace.

Syntax

Description

clear functionname

Remove specified function from workspace.

clear functions

Remove all compiled M-functions.

clear all

Remove all variables and functions.

Determining Which Function Is Called

When more than one function has the same name, which one does MATLAB call? This section explains the process that MATLAB uses to make this decision. It covers the following topics:

Also keep in mind that there are certain situations in which function names can conflict with variables of the same name. See Potential Conflict with Function Namesfor more information.

Function Scope

Any functions you call must first be within the scope of (i.e., visible to) the calling function or your MATLAB session. MATLAB determines if a function is in scope by searching for the function's executable file according to a certain order (see Precedence Order).

One key part of this search order is the MATLAB path. The path is an ordered list of directories that MATLAB defines on startup. You can add or remove any directories you want from the path. MATLAB searches the path for the given function name, starting at the first directory in the path string and continuing until either the function file is found or the list of directories is exhausted. If no function of that name is found, then the function is considered to be out of scope and MATLAB issues an error.

Precedence Order

The function precedence order determines the precedence of one function over another based on the type of function and its location on the MATLAB path. MATLAB selects the correct function for a given context by applying the following function precedence rules in the order given here.

For items 3 through 7 in this list, the file MATLAB searches for can be any of four types: an M- or built-in file, preparsed M-file (P-Code), compiled C or Fortran file (MEX-file), or Simulink® model (MDL-file). See Multiple Implementation Types for more on this.

  1. Variable

    Before assuming that a name should match a function, MATLAB checks the current workspace to see if it matches a variable name. If MATLAB finds a match, it stops the search.

  2. Subfunction

    Subfunctions take precedence over all other M-file functions and overloaded methods that are on the path and have the same name. Even if the function is called with an argument of type matching that of an overloaded method, MATLAB uses the subfunction and ignores the overloaded method.

  3. Private function

    Private functions are called if there is no subfunction of the same name within the current scope. As with subfunctions, even if the function is called with an argument of type matching that of an overloaded method, MATLAB uses the private function and ignores the overloaded method.

  4. Class constructor

    Constructor functions (functions having names that are the same as the @ directory, for example @polynom/polynom.m) take precedence over other MATLAB functions. Therefore, if you create an M-file called polynom.m and put it on your path before the constructor @polynom/polynom.m version, MATLAB will always call the constructor version.

  5. Overloaded method

    MATLAB calls an overloaded method if it is not superseded by a subfunction or private function. Which overloaded method gets called depends on the classes of the objects passed in the argument list.

  6. Function in the current directory

    A function in the current working directory is selected before one elsewhere on the path.

  7. Function elsewhere on the path

    Finally, a function elsewhere on the path is selected. A function in a directory that is toward the beginning of the path string is given higher precedence.

Multiple Implementation Types

There are five file precedence types. MATLAB uses file precedence to select between identically named functions in the same directory. The order of precedence for file types is

  1. Built-in file

  2. MEX-files

  3. MDL (Simulink® model) file

  4. P-code file

  5. M-file

For example, if MATLAB finds a P-code and an M-file version of a method in a class directory, then the P-code version is used. It is, therefore, important to regenerate the P-code version whenever you edit the M-file.

Querying Which Function MATLAB Will Call

You can determine which function MATLAB will call using the which command. For example,

which pie3
matlabroot/toolbox/matlab/specgraph/pie3.m

However, if p is a portfolio object,

which pie3(p)
dir_on_your_path/@portfolio/pie3.m      % portfolio method

The which command determines which version of pie3 MATLAB will call if you passed a portfolio object as the input argument. To see a list of all versions of a particular function that are on your MATLAB path, use the -all option. See the which reference page for more information on this command.

MATLAB Calling Syntax

This section explains how to use the MATLAB command and function syntax:

You can call function M-files from either the MATLAB command line or from within other M-files. Be sure to include all necessary arguments, enclosing input arguments in parentheses and output arguments in square brackets.

You often have the choice of using one of two syntaxes for a function call. You can use either a command or a function type of syntax. This is referred to in MATLAB as command/function duality.

MATLAB Command Syntax

A function call made in command syntax consists of the function name followed by one or more arguments separated by spaces:

functionname in1 in2 ... inN

While the command syntax is simpler to write, it has the restriction that you may not assign any return values the function might generate. Attempting to do so generates an error.

Two examples of command syntax are

save mydata.mat x y z
clear length width depth

In the command syntax, MATLAB treats all arguments as string literals.

MATLAB Function Syntax

Function calls written in the function syntax look essentially the same as those in many other programming languages. One difference is that, in MATLAB, functions can return more than one output value.

A function call with a single return value looks like this:

out = functionname(in1, in2, ..., inN)

If the function returns more than one value, separate the output variables with commas or spaces, and enclose them all in square brackets ([]):

[out1, out2, ..., outN] = functionname(in1, in2, ..., inN)

Here are two examples:

copyfile(srcfile, '..\mytests', 'writable')
[x1, x2, x3, x4] = deal(A{:})

In the function syntax, MATLAB passes arguments to the function by value. See the examples under Passing Arguments with Command and Function Syntax.

Passing Arguments with Command and Function Syntax

When you call a function using function syntax, MATLAB passes the values assigned to each variable in the argument list. For example, this expression passes the values assigned to A0, A1, and A2 to the polyeig function:

e = polyeig(A0, A1, A2)

Function calls written in command syntax pass all arguments as string literals. This expression passes the strings 'mydata.mat', 'x', 'y', and 'z' to the save function:

save mydata.mat x y z

The following examples show the difference between passing arguments in the two syntaxes.

Passing Arguments — Example 1.   Calling disp with the function syntax, disp(A), passes the value of variable A to the disp function:

A = pi;

disp(A)                    % Function syntax
   3.1416

Calling it with the command syntax, disp A, passes the string 'A':

A = pi;

disp A                     % Command syntax
   A

Passing Arguments — Example 2.   Passing two variables representing equal strings to the strcmp function using function and command syntaxes gives different results. The function syntax passes the values of the arguments. strcmp returns a 1, which means they are equal:

str1 = 'one';       str2 = 'one';

strcmp(str1, str2)                  % Function syntax
ans =
   1        (equal)

The command syntax passes the names of the variables, 'str1' and 'str2', which are unequal:

str1 = 'one';       str2 = 'one';

strcmp str1 str2                    % Command syntax
ans =
   0        (unequal)

How MATLAB Recognizes Function Calls That Use Command Syntax

It can be difficult to tell whether a MATLAB expression is a function call using command syntax or another kind of expression, such as an operation on one or more variables. Consider the following example:

ls ./d

Is this a call to the ls function with the directory ./d as its argument? Or is it a request to perform elementwise division on the array that is the value of the ls variable, using the value of the d variable as the divisor?

This example might appear unambiguous because MATLAB can determine whether ls and d are functions or variables. But that is not always true. Some MATLAB components, such as M-Lint and the Editor/Debugger, must operate without reference to the MATLAB path or workspace. MATLAB therefore uses syntactic rules to determine when an expression is a function call using command syntax.

The rules are complicated and have exceptions. In general, when MATLAB recognizes an identifier (which might name a function or a variable), it analyzes the characters that follow the identifier to determine what kind of expression exists. The expression is usually a function call using command syntax when all of the following are true:

  1. The identifier is followed immediately by white space.

  2. The characters following the white space are not parentheses or an assignment operator.

  3. The characters following the white space are not an operator that is itself followed by additional white space and then by characters that can legitimately follow an operator.

The example above meets all three criteria and is therefore a function call using command syntax:

ls ./d

The following examples are not function calls using command syntax:

% No white space following the ls identifier
% Interpretation: elementwise division
ls./d

% Parenthesis following white space
% Interpretation: function call using function syntax
ls ('./d')

% Assignment operator following white space
% Interpretation: assignment to a variable
ls =d

% Operator following white space, followed in turn by
% more white space and a variable
% Interpretation: elementwise division
ls ./ d

Passing Certain Argument Types

This section explains how to pass the following types of data in a function call:

Passing Strings

When using the function syntax to pass a string literal to a function, you must enclose the string in single quotes, ('string'). For example, to create a new directory called myapptests, use

mkdir('myapptests')

On the other hand, variables that contain strings do not need to be enclosed in quotes:

dirname = 'myapptests';
mkdir(dirname)

Passing Filenames

You can specify a filename argument using the MATLAB command or function syntax. For example, either of the following are acceptable. (The .mat file extension is optional for save and load):

load mydata.mat           % Command syntax
load('mydata.mat')        % Function syntax

If you assign the output to a variable, you must use the function syntax:

savedData = load('mydata.mat')

Specify ASCII files as shown here. In this case, the file extension is required:

load mydata.dat -ascii            % Command syntax
load('mydata.dat','-ascii')       % Function syntax

Determining Filenames at Run-Time.   There are several ways that your function code can work on specific files without your having to hardcode their filenames into the program. You can

Passing Function Handles

The MATLAB function handle has several uses, the most common being a means of immediate access to the function it represents. You can pass function handles in argument lists to other functions, enabling the receiving function to make calls by means of the handle.

To pass a function handle, include its variable name in the argument list of the call:

fhandle = @humps;
x = fminbnd(fhandle, 0.3, 1);

The receiving function invokes the function being passed using the usual MATLAB calling syntax:

function [xf, fval, exitflag, output] = ...
         fminbnd(fhandle, ax, bx, options, varargin)
            .
            .
            .
113  fx = fhandle(x, varargin{:});

Passing Arguments in Structures or Cell Arrays

Instead of requiring an additional argument for every value you want to pass in a function call, you can package them in a MATLAB structure or cell array.

Passing Arguments in a Structure

Make each input you want to pass a separate field in the structure argument, using descriptive names for the fields. Structures allow you to change the number, contents, or order of the arguments without having to modify the function. They can also be useful when you have a number of functions that need similar information.

This example updates weather statistics from information in the following chart.

City

Temp.

Heat Index

Wind Speed

Wind Chill

Boston

43

32

8

37

Chicago

34

27

3

30

Lincoln

25

17

11

16

Denver

15

-5

9

0

Las Vegas

31

22

4

35

San Francisco

52

47

18

42

The information is stored in structure W. The structure has one field for each column of data:

W = struct('city', {'Bos','Chi','Lin','Dnv','Vgs','SFr'}, ...
           'temp', {43, 34, 25, 15, 31, 52}, ...
           'heatix', {32, 27, 17, -5, 22, 47}, ...
           'wspeed', {8, 3, 11, 9, 4, 18}, ...
           'wchill', {37, 30, 16, 0, 35, 42});

To update the data base, you can pass the entire structure, or just one field with its associated data. In the call shown here, W.wchill is a comma-separated list:

updateStats(W.wchill);

Passing Arguments in a Cell Array

You can also group arguments into cell arrays. The advantage over structures is that cell arrays are referenced by index, allowing you to loop through a cell array and access each argument passed in or out of the function. The disadvantage is that you don't have field names to describe each variable.

This example passes several attribute-value arguments to the plot function:

X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));

C{1,1} = 'LineWidth';         C{2,1} = 2;
C{1,2} = 'MarkerEdgeColor';   C{2,2} = 'k';
C{1,3} = 'MarkerFaceColor';   C{2,3} = 'g';

plot(X, Y, '--rs', C{:})

Assigning Output Arguments

Use the syntax shown here to store any values that are returned by the function you are calling. To store one output, put the variable that is to hold that output to the left of the equal sign:

vout = myfun(vin1, vin2, ...);

To store more than one output, list the output variables inside square brackets and separate them with commas or spaces:

[vout1 vout2 ...] = myfun(vin1, vin2, ...);

The number of output variables in your function call statement does not have to match the number of return values declared in the function being called. For a function that declares N return values, you can specify anywhere from zero to N output variables in the call statement. Any return values that you do not have an output variable for are discarded.

Functions return output values in the order in which the corresponding output variables appear in the function definition line within the M-file. This function returns 100 first, then x * y, and lastly x.^2:

function [a b c] = myfun(x, y)
b = x * y;    a = 100;    c = x.^2;

If called with only one output variable in the call statement, the function returns only 100 and discards the values of b and c. If called with no outputs, the functions returns 100 in the MATLAB default variable ans.

Assigning Optional Return Values

The section Passing Variable Numbers of Arguments describes the method of returning optional outputs in a cell array called varargout. A function that uses varargout to return optional values has a function definition line that looks like one of the following:

function varargout = myfun(vin1, vin2, ...)
function [vout1 vout2 ... varargout] = myfun(vin1, vin2, ...)

The code within the function builds the varargout cell array. The content and order of elements in the cell array determines how MATLAB assigns optional return values to output variables in the function call.

In the case where varargout is the only variable shown to the left of the equal sign in the function definition line, MATLAB assigns varargout{1} to the first output variable, varargout{2} to the second, and so on. If there are other outputs declared in the function definition line, then MATLAB assigns those outputs to the leftmost output variables in the call statement, and then assigns outputs taken from the varargout array to the remaining output variables in the order just described.

This function builds the varargout array using descending rows of a 5-by-5 matrix. The function is capable of returning up to six outputs:

function varargout = byRow(a)
varargout{1} = '    With VARARGOUT constructed by row ...';
for k = 1:5
    row = 5 - (k-1);              % Reverse row order
    varargout{k+1} = a(row,:);
end

Call the function, assigning outputs to four variables. MATLAB returns varargout{1:4}, with rows of the matrix in varargout{2:4} and in the order in which they were stored by the function:

[text r1 r2 r3] = byRow(magic(5))
text =
    With VARARGOUT constructed by row ...
r1 =
    11    18    25     2     9
r2 =
    10    12    19    21     3
r3 =
     4     6    13    20    22

A similar function builds the varargout array using diagonals of a 5-by-5 matrix:

function varargout = byDiag(a)
varargout{1} = '    With VARARGOUT constructed by diagonal ...';
for k = -4:4
    varargout{k + 6} = diag(a, k);
end

Call the function with five output variables. Again, MATLAB assigns elements of varargout according to the manner in which it was constructed within the function:

[text d1 d2 d3 d4] = byDiag(magic(5))
text =
    With VARARGOUT constructed by diagonal ...
d1 =
    11
d2 =
    10
    18
d3 =
     4
    12
    25
d4 =
    23
     6
    19
     2

Calling External Functions

The MATLAB external interface offers a number of ways to run external functions from MATLAB. This includes programs written in C or Fortran, methods invoked on Java or COM (Component Object Model) objects, functions that interface with serial port hardware, and functions stored in shared libraries. The MATLAB External Interfaces documentation describes these various interfaces and how to call these external functions.

Running External Programs

For information on how to invoke operating systems commands or execute programs that are external to MATLAB, see Running External Programs in the MATLAB Desktop Tools and Development documentation.

  


© 1984-2007 The MathWorks, Inc. Terms of Use Patents Trademarks Acknowledgments

Your Ad Here