## Loren on the Art of MATLABTurn ideas into MATLAB

Note

Loren on the Art of MATLAB has been archived and will not be updated.

# Command and Function Syntaxes in MATLAB

There is a fairly constant stream of questions in many MATLAB venues, including the MATLAB newsgroup that boil down to not understanding the difference between command and function syntaxes in MATLAB. Today I try to set the record straight.

### Typical Question

Why is MATLAB giving me the wrong answer here?

A = 1:4;
disp A
A


Why don't I see the values 1,...,4 found in variable A?

### MATLAB Documentation

Before answering the user's question and discussing the details, I must admit that I think the documentation on MATLAB Calling Syntax is very clear on this topic. Nonetheless, I will give my own take here.

### MATLAB Function Syntax

We call MATLAB functions by listing their input arguments inside parentheses and separated by commas. For example,

sin(pi*(0:5)/5)

gives us a crudely sampled half sine wave. To put that into a variable, use a variable name (or index into an existing variable) followed by an equal sign (=) and then the expression being computed.

hs = sin(pi*(0:5)/5)
hs =
0    0.5878    0.9511    0.9511    0.5878    0.0000


For multiple output variables, use a variables separated by commas and surrounded by square brackets for the output arguments:

[a,b,c] = deal(17)
a =
17
b =
17
c =
17


Instead of explicit inputs, we can use variables and variable expressions.

tpoints = (0:25)/5;
halfsine = sin(pi*tpoints(1:6))
halfsine =
0    0.5878    0.9511    0.9511    0.5878    0.0000


and if we wanted to compute this in single precision instead of using doubles, we can do something like this:

tps = single(tpoints);
halfsines = sin(pi*tps(1:6))
halfsines =
0    0.5878    0.9511    0.9511    0.5878   -0.0000


If we have a function that takes a string input, such as dir, we can either pass in the string explicitly:

dir('D:\Loren\BootCamp')
.           ..          fromDoug    fromStuart



or we can pass in a string variable.

dirname = 'D:\Loren\BootCamp'
dir(dirname)
dirname =
D:\Loren\BootCamp

.           ..          fromDoug    fromStuart



### MATLAB Command Syntax

Command syntax doesn't use parentheses, frequently doesn't place output in a variable, can't return multiple variables, and handles only literal string inputs. For example,

disp(dirname)
D:\Loren\BootCamp


displays the string value of the variable dirname, while

disp dirname
dirname


displays the literal string dirname.

Similarly, we can see the difference between the following 2 statements:

disp A
disp(A)
A
1     2     3     4


where the first statement displays the literal string A and the second statement displays the values that A contains.

### Equivalent MATLAB Statements Using Command and Function Syntax

Here are some equivalent MATLAB statements for combining a string and a number to create a filename to pass to load.