Calling Functions

Command vs. Function Syntax

Overview

MATLAB® syntax differs for issuing commands and for calling functions. This is sometimes referred to as command-function duality. In many cases, you can use either of the two syntaxes in commands and in function calls.

You are issuing a command when you tell MATLAB to do something. You might use a function name in the command and possibly a few switches or modifiers, usually expressed in the form of character strings. But, in most cases, there is no need to pass data such as numeric values or variables in a command. There is also no expectation that the command returns any output value.

A few examples of MATLAB commands are shown here. Note that MATLAB passes only string arguments and does not return any output:

clear
format long
dbstop in find_maxval
addpath C:\srcdir D:\matlab\testdir2 -end
whos -file savefile.mat -regexp ^p*

Unlike commands, most functions act upon data. You pass data into the function when calling it, and often expect it to return data upon completion. These input and output values can be in the form of any MATLAB class (e.g., arrays of integers, characters, cells, function handles, etc.).

Examples of function calls are shown below. Note that MATLAB requires parentheses around the input argument list, quotation marks around characters and strings, and brackets around multiple output values:

y = eye(n)
C = complex(A, B);
m = memmapfile('records.dat', 'Offset', 1024, 'Format', 'uint32');
[x1 x2 x3 x4] = deal(A{:});

Regardless of which syntax you use, function names are always sensitive to case. When you call a function, use the correct combination of upper and lowercase letters so that the name is an exact match. Otherwise, you risk calling a different function that does match, but is elsewhere on the path.

MATLAB® Command Syntax

A command that makes a function call consists of the function name followed by one or more arguments separated by spaces. In most cases, all input arguments are considered to be strings. Because of this, enclosing string arguments with quotation marks is optional.

The format for calling a function using command syntax is

functionname string1 string2 string3 

You can use command syntax in calling a function when both of the following are true:

When you use command syntax, MATLAB interprets each input argument as a character string literal. There is no need to enclose these string arguments in quotation marks unless the argument includes one or more space characters. This is true whether the argument is a string of plain text, a file name, or a command switch:

strcat one two three four          % Command with 4 arguments.
ans =
   onetwothreefour

strcat 'one' 'two' 'three' 'four'  % Command with 4 arguments.
ans =
   onetwothreefour

strcat 'one two three four'        % Command with 1 argument.
ans =
   one two three four

Several examples of command syntax are given below.

Example 1.   This command copies file square.m to directory D:\matlab\functions. All arguments are strings:

copyfile square.m D:\matlab\functions

Example 2.   The example on the left calls disp using command syntax. MATLAB interprets A as a string literal and displays the character A.

The example on the right passes the value of A to disp, which then displays 3.1416:

Command SyntaxFunction Syntax
A = pi;

disp A
A
A = pi;

disp(A)
3.1416

Using save and load with Command Syntax.   There are a few functions, such as save and load, that do accept variable names as input arguments. Examples follow:

save mydata.mat x y z         % x, y, and z are variables
load mydata x z               % x and z are variables
clear N                       % N is a variable
whos A                        % A is a variable

MATLAB® Function Syntax

Function calls written in function syntax

Unlike command syntax, there are no limitations on when you can use function syntax in a function call.

Function calls written in function syntax enclose the input argument list in parentheses, separate the inputs with commas, enclose string arguments with single quotation marks, and optionally assign any output from the function to one or more output arguments. Unlike command syntax, there are no limitations on when you can use function syntax in a function call.

The format for MATLAB function syntax is

out = functionname(variable, 'string', expression, ...);

Calls written in function syntax pass 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)

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

For example,

[pathstr, name, ext, versn] = fileparts(filename);

Several examples of function syntax appear below. For more examples, see the section on Common Mistakes In Syntax

Example 1 — Simple Variable Comparison.   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)

Example 2 — Passing Variable Names.   The reshape function takes three input arguments: a variable name and two integers to specify dimensions for the new shape. It also returns the reshaped array. For both of these reasons, you need to use function syntax for this operation:

S1 = 'MATLAB: Accelerating the pace of engineering and science.';

S2 = reshape(S1, 19, 3);
S2'
ans =
MATLAB: Acceleratin
g the pace of engin
eering and science.

Command syntax interprets all three input arguments as strings and provides no means for capturing the output:

reshape S1 19 3;
??? Error using ==> reshape
Size arguments must be integer scalars.

Common Mistakes In Syntax

The two MATLAB syntax styles are generally easy to use. You should have no difficulty in using them if you keep in mind the rules stated in the previous sections. Just the same, there are certain potential errors to watch out for.

In all examples in this section, it is the group of statements on the left that are incorrect, and the statements on the right that show the correct usage.

Example 1 — Numeric Values Evaluated As Strings.   The statement on the left, below, appears to report that 500 is not numeric. However, because this statement uses command syntax, the input is actually the string '500' and not the number. Use function syntax, as shown on the right, to get the correct answer:

isnumeric 500                 isnumeric(500)
ans =                         ans =
    0                             1

Example 2 — Equal Values that Appear As Unequal.   In this example, it might seem that MATLAB is reporting the values of variables A and B as unequal. However, it is not the values of A and B that are being compared here; it is the variable names 'A' and 'B':

A = 500;   B = 500;              A = 500;   B = 500;
isequal A B                      isequal(A, B)
ans =                            ans =
     0                                1

Example 3 — Command Switches Used in Function Syntax.   When using a command switch or modifier with function syntax, remember to enclose not only the input arguments in quotation marks, but the command switch, as well. In this example, -file needs to have quotation marks around it:

whos(-file, 'savefile.mat')      whos('-file', 'tempfile.mat')

A simpler method is to use command syntax for this type of statement:

whos -file tempfile.mat

Example 4 — Translation of Keywords.   In command syntax, MATLAB interprets keywords in the same way it does variable names, as string literals. The statement to the left instructs MATLAB to search for a directory with the literal name 'matlabroot', when what was intended was the directory specified by this keyword. Function syntax uses the value of the keyword instead:

cd matlabroot                    cd(matlabroot)

Example 5 — Variables That Hold Filenames.   This example, uses the fopen function to open the file accounts.txt. When this is done using command syntax, MATLAB looks for a file named filename, which does not exist. When working with filenames that are stored in variables, it is usually best to use function syntax:

filename = 'accounts.txt';       filename = 'accounts.txt';
fopen filename;                  fopen('filename');

Example 6 — Invalid String Comparisons.   This example attempts to see if the class of vector A is an 8-bit unsigned integer (uint8), but the comparison is really between the strings 'class(A)' and 'int8':

A = int8(1:8)                    A = int8(1:8)
strcmp class(A) int8             strcmp(class(A), 'int8')
ans =                            ans =
     0                                1

Example 7 — Numeric Arguments.   This example shows that command syntax does not accept numeric arguments. Because command syntax assumes that each input argument is a character string, the numeric input 3.499 is interpreted by MATLAB as a five-element character array '3.499', numerically equivalent to the vector [51 46 52 57 57].

round 3.499                      round(3.499)
ans =                            ans =
   51   46   52   57   57           3

Example 8 — Save and Load.   The save and load functions are often easier to use with command syntax. The statement save M saves variable M, not the character M, to the workspace:

M = magic(20);                   M = magic(20);
save(M)                          save M          % or save('M')
clear M                          clear M
load(M)                          load M          % or load('M')

Example 9 — Class as a Command.   When using the class function to display or return the class of a variable or value, always use the function syntax:

class pi                         class(pi)
ans =                            ans =
   char                             double

Recognizing 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

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 Gets 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:

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 Names for 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 Function Precedence Order, below).

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.

Function 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 Gets Called

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.

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 Sun™ 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-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS