Quantcast

Documentation Center

  • Trial Software
  • Product Updates

syntax

Two ways to call MATLAB functions

Description

You can call MATLAB® functions using either command syntax or function syntax, as described below.

Command Syntax

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

functionname arg1 arg2 ... argn

Command syntax does not allow you to obtain any values that might be returned by the function. Attempting to assign output from the function to a variable using command syntax generates an error. Use function syntax instead.

Examples of command syntax:

save mydata.mat x y z
import java.awt.Button java.lang.String

Arguments are treated as string literals. See the examples below, under Argument Passing.

Function Syntax

A function call in this syntax consists of the function name followed by one or more arguments separated by commas and enclosed in parentheses:

functionname(arg1, arg2, ..., argn)

You can assign the output of the function to one or more output values. When assigning to more than one output variable, separate the variables by commas or spaces and enclose them in square brackets ([]):

[out1,out2,...,outn] = functionname(arg1, arg2, ..., argn)

Examples of function syntax:

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

Arguments are passed to the function by value. See the examples below, under Argument Passing.

Argument Passing

When calling a function using command syntax, MATLAB passes the arguments as string literals. When using function syntax, arguments are passed by value.

In the following example, assign a value to A and then call disp on the variable to display the value passed. Calling disp with command syntax passes the variable name, 'A':

A = pi;
disp A
   A

while function syntax passes the value assigned to A:

A = pi;
disp(A)
   3.1416

The next example passes two strings to strcmp for comparison. Calling the function with command syntax compares the variable names, 'str1' and 'str2':

str1 = 'one';    str2 = 'one';
strcmp str1 str2
ans =
     0        (unequal)

while function syntax compares the values assigned to the variables, 'one' and 'one':

str1 = 'one';    str2 = 'one';
strcmp(str1, str2)
ans =
     1        (equal)

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 folder called myapptests, use

mkdir('myapptests')

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

folder = 'myapptests';
mkdir(folder)

See Also

Was this topic helpful?