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.
Why is MATLAB giving me the wrong answer here?
A = 1:4; disp A
Why don't I see the values 1,...,4 found in variable A?
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.
We call MATLAB functions by listing their input arguments inside parentheses and separated by commas. For example,
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:
. .. fromDoug fromStuart
or we can pass in a string variable.
dirname = 'D:\Loren\BootCamp' dir(dirname)
dirname = D:\Loren\BootCamp . .. fromDoug fromStuart
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,
displays the string value of the variable dirname, while
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.
Here are some equivalent MATLAB statements for combining a string and a number to create a filename to pass to load.
fn = 'file4'; load(fn)
fn = 'file'; nfiles = 4; load([fn int2str(nfiles)])
Do you have any thoughts on how we can prevent users from tripping over command vs. function syntax in MATLAB? If so, please let me know.
Published with MATLAB® 7.2