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.
Contents
Typical Question
Why is MATLAB giving me the wrong answer here?
A = 1:4;
disp AA
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 dirnamedirname
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.
load('file4')
load file4
fn = 'file4'; load(fn)
fn = 'file'; nfiles = 4; load([fn int2str(nfiles)])
How to Help Users Not Trip on Command vs. Function Syntax
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



Hi Loren,
If I have a simple function
function a = foo(y)
…if nargin==0
……y = 5
…end
…a = 10 + y
end
and then at the matlab command line I type
foo + 10
how does matlab figure out I don’t mean
foo(’+ 10′)
but
foo + 10
or does it do foo(’+ 10′). I haven’t checked myself!
Regards
Brad
Brad-
Good question, difficult to answer. MATLAB tries to do what you “expect”. One way to see what will happen is to write the function and look at the command line as you execute the function. Sorry for my lack of colorization below.
When you first type:
you will see the + in purple to indicate it’s a string. If you continue like this:
the second “string” still gets parsed as a string. If instead you do this:
you will notice that as soon as you type the second space, that the + no longer is purple, indicating that it is interpreted as an operator. MATLAB has knowledge of the syntax and quirks of the language and we use that information to help decide whether to continue interpreting a line with string inputs, or as a mathematical expression.
Seems a little unpredictable. Perhapps with hindsight it would have been better never to have had string command mode. Then the possibility would have been open to have had parentheses free function calls.
function b=foo(a)
…b = a+1
end
foo 10
ans =
11
and more exotic things like function currying
function f=sum(a)
…f=@(b)b+a
end
> f = sum 10;
> f 11;
ans =
21
or
> sum 10 11
ans =
21
Loren,
I read in detail your comments regarding “Command and Function Syntaxes in MatLab.” I also read the referenced MatLab documentation.
I’m a 25 year Boeing engineer who has been using MatLab for ~3 years. Last August, Boeing installed a copy on my Boeing provided laptop and I spend ~40 hours a week programming MatLab.
I certainly have been tripped up by this issue many times. I’m guessing I’ve lost on the order of 200 hours de-bugging these problems.
I started writing a narrowly focused reply to just this topic, but I’ve spent ~8 hours surfing thru your columns, finding several related issues. I can imagine that you are swamped with replies to your columns and the length of my response must be a strong argument against reading it. Let me offer this as an encouragement to read on:
Amongst the ~400 engineer Aerodynamics Engineering organization of Boeing Commercial Aerodynamics, I am one of the pioneering MatLab users. My bosses keep looking to my experience and asking for my opinion regarding a wider deployment of MatLab within Aerodynamics. Certainly the young kids we are hiring have used MatLab in school, but none seem to qualify as expert users. They can hack their way thru straight forward problems. But, it is difficult to pass their MatLab code on to others. In short, like many young engineers, they need several years of coaching to mature. Because of this, they aren’t the ones our bosses ask about deployment of MatLab. They ask folks like me.
Like I said, I’ve read your posting & the documentation, but I don’t think I understand the issue properly yet. For example, I couldn’t explain to a co-worker, the differences between these two syntaxes for any but the most simple functions, like sin.
I’ve encountered this issue with other MatLab documentation and I have a theory about why this documentation doesn’t meet my needs:
The MatLab programmers & technical writers are all ace C programmers and they understand many of these concepts very, very well. They have trouble understanding the perspective of a user, like me, who doesn’t have a deep understanding of C. Ask me how big the tail needs to be on an airplane and I’ll give you a bullet proof, defensible answer and at the end of the project, you and your grandmother can go for a ride on it. But, don’t ask my professional opinion about C.
Regarding command and function Syntaxes, I’ve read enough to conclude that the topic is critically important. MatLab’s documentation on this should have a series of about 20 examples that methodically and comprehensively take the user from the brief introduction to the very detailed. Then the user has a reliable resource to learn the topic. The about 5 examples in the current documentation are too shallow. Your posting does add some detail, but not enough.
There are similar short comings in the MatLab documentation regarding data types and classes. Again, I understand this is a useful feature of C so I guess an experienced C programmer can pick this up quickly. But, I’m not that person. I recently became aware of the data structure in MatLab and I was surprised to find that MatLab didn’t have a command that would automatically package an arbitrary list of variables, like the output from the who command, into a single structure. Also missing was a command to automatically burst a structure into the component variables. So, I wrote some functions of my own to do these two actions and I was surprised at the difficulty. All my problems related to the issue of data types and classes as applied to cell arrays, characters etc. I spent ~10 hours on these two functions & ~3 hours trying to understand this topic from the MatLab documentation. I did finish the functions, they seem to work for the type of data I have on my project and it didn’t take many lines of code. However, I’m concerned that they won’t work when we get other types of data types or classes.
While working on these functions I kept thinking that I am not the intended audience for this documentation. Then, I asked, who is the intended audience? The documentation has a nice tree sketch showing different data types. But, it appears to be an e.g. type of explanation, not an i.e., type. The top of the documentation says there are 15 fundamental data types. But, when I first counted what I thought would be the fundamental level in the tree sketch, I got 7. So, I then counted the second level and I got 10. I concluded that this again couldn’t be right, so I picked and poked around and finally end up counting what appear to be the 15 fundamental data types. Then, I read that the lower case is used to identify the fundamental ones and that confirms my counting to 15. Why not have a legend for the sketch?
The table is a step in the right direction, but the text in the description is way too sparse. Look at the first row in the table. Now I’ve got to educate myself about what the difference really is between signed and unsigned. I could guess, but I shouldn’t have to guess when reading documentation. Even worse, the documentation doesn’t state which are signed and which are unsigned. Again, I could guess. Next, I read that some integer types use less memory. That is nice to know, but the documentation doesn’t tell me which ones! Now, in MatLab’s defense, the hyperlinks do take the reader to much more detail regarding these and that detail appears to be adequate for some of the data types. Interestingly enough, while reading these details, the documentation discusses the MatLab function whos but the output of whos doesn’t tell me what data type a variable is, rather it tells me what class it is. And, I haven’t been able to discover what the similarities & differences are between data types and classes.
Another example of inadequate documentation relates to function handles. I’ve been aware of them in MatLab for ~2 years and I’ve read the documentation several times, including several aftermarket MatLab books. I think I understand part of how they work. But, I can’t imagine how they are beneficial, or attractive. For example, I can see how it would be useful, for example, to calculate the absolute value of the output from the sin function. I could do it by:
y = abs(sin(x));
It appears I could also do it using function handles. But, I’m not sure of the syntax and I think I’d first have to take a line to define the function handle. So, how is the function handle useful in this example?
Further, the MatLab documentation is confusing. e.g., this is listed as one of the options under “Syntax”:
handle = @anonymous_function
Later in the documentation, it states that this syntax: “… returns a handle to the specified MATLAB function.”
In Example 1 the following is listed:
fhandle = @humps;
But, humps isn’t listed as a MatLab function. After ~ 3 hours of picking & poking it appears that humps is a type of MatLab provided sub-function. And, because of the style in which it is written, I can’t tell for sure what is happening with it. Now Loren, that just isn’t fair. Why hide the useful information and obscure what is going on?
Is the intent to show how a function handle works with a user written function and MatLab provided a “silly” one called humps for use as an example? But, what about the statement about MatLab function? Maybe even user written functions are considered MatLab functions in this context. If so, what is this function humps to do?
I’ve read this section of documentation many times over the past 2 years & I don’t understand what message is being communicated in Example 1. Part of the text in Example 1 discusses evaluating the function handle, but I don’t know what that means. It apparently is different than evaluating a function or the different terminology wouldn’t be necessary. And, it apparently is different than evaluating the function represented by the function handle. My frustration is furthered by the apparent importance and power of function handles, yet I can’t find what the secret is within the MatLab documentation. One hint at the power of function handles relates to the function fminbnd. It appears I can’t use this function unless I understand the topic of function handles, which, of course, is what first lead me to read the function handle documentation for the first time, ~2 years ago. Again, if function handles are powerful and important, MatLab should have on the order of 20 examples the comprehensively lead the reader thru the topic.
Let me temper the above detailed criticism with some observations. Clearly, documentation can’t ever be perfect. And, different users will understand the same documentation differently. Further, MatLab’s documentation for many provided functions are very well written. I can read about the sort or sin or eig function and quickly engage with them.
But for the topics I’ve discussed in detail, the documentation isn’t adequate. The scope of the documentation and amount of documentation should be somehow related to the complexity of the concept. Further, if The MathWorks is a competent software house, and I’m sure it is, then all production code must be written from written requirements and specifications. I’m sure that many MathWorks folks develop prototype code, but when a prototype concept is chosen for production, requirements & specifications are developed. If that happens, why not have the technical writers use those requirements & specifications to write the documentation? What I have illustrated with the above examples is a disconnect between the complexity of a concept and the depth of the documentation.
If you can provide any insight into the specific topics of data types and function handles, please let me know.
Thanks for taking the time to read this.
Oliver A. Chapman, PE
(425) 237-4969
Oliver,
Here are a few of my own articles which use function handles and show some simple and not so simple uses of them. Skip the top article in the link which is advanced stuff but the other three show how you can build your own function which accept function handles as parameters and do neat stuff with them.
http://xtargets.com/snippets/tags/handle/function
Cheers
Brad
And here is another link with some more ( and some the same ) examples.
http://xtargets.com/snippets/tags/function/nested
B
Brad,
First of all, thank you very much for directing me to these examples.
I’ve spent about 2 hours looking at your example regarding folding arrays and I can’t understand what useful thing the code is doing. Did you intend to name the function after a verb that is meaningful to you? If so, maybe you could define the term fold.
From the context of your usage examples, the code appears to echo the contents of the input cell array, in the second example, preceded by a comma. Is the code designed to convert a list contained in the cell array into a comma separated list? If so, why not call the function something like: cell2csv? Or at least mention on the web page that that is the intent.
I do understand several things in the code: I understand how the start and end values for the for loop are defined. I also understand how the same effect is applied depending on if the input is a cell array or a character array.
But, I don’t follow the data flow thru the written function. The function fold as written has 3 input arguments and in the usage section, you clearly demonstrate how the second argument is defined as the function handle for the function fold. But, in the bottom of the function, when you call that function via the handle, you only pass two arguments. How can that work? I do see how the function fold does a test for two input arguments, but in your usage examples, doesn’t the first one pass 3 inputs and the second example passes 4? And, what is with the 4th argument? It isn’t a space, yet it is some type of null character. It has a class of char and a size of zero, if I convert it to a number, it also has a class of double and a size of zero. I’ve never encountered such a thing before.
My confusion with this example illustrates my confusion with the concept of a function handle: I can’t understand how the concept works for functions with multiple input arguments and if the function only has one input, why use function handles instead of imbedding one function in the argument of the next?
Further, how can this be easy to understand code?
Anyway, thanks again for attempting to help. I’ll keep picking and poking around these, show these to some co-workers and maybe I’ll get to the point where I understand the key point.
Oliver A. Chapman, PE
Hi Oliver,
Folding is a fancy programming term for a generalized accumulator. You can take an array and cumulatively apply a function on each element of the array, building a result as you go.
In the example the accumulator function ( anonymous function )
f@(str, item) [ str ‘,’ item ]
is a function that takes two arguments.
- str : the previous output of the accumulator function
- item : the next item from the array
and builds a string of the two items seperated by a comma.
If you wanted to use the fold function to do a cumulative sum then you could do
To use fold to cummulative sum an array
a = 1..5
fold(a,@(s, next) s + next ,0 )
To use fold to calculate fibonnaci sequences
a = 1..10
fold(a,@(s, next) [s s(end) + s(end-1)] , [1 1] )
In general the algorithm of fold is
output = fh( fh( fh( init, array(1) ), array(2) ) )
I’m sorry. I may also have confused you by using the same name “fold” for a function and for a parameter. I’ve cleared that up on the web page.
Brad
Brad,
Thank you again for the help.
A co-worker who isn’t familiar with MatLab, but is proficient with C & C++ looked at your examples and between the two of us, I think we understand a key concept: The function handle isn’t being defined for the function “fold” but rather it is defined for this anonymous concatenation function represented by: [ str ‘,’ item ]. Neither of us had heard of the term fold used for concatenation.
If I were doing the example I would illustrate the point by expanding the example into 3 parts.
Example 1:
First, define a concatenation function:
function output = mycat(str, item);
%
% User defined function to concatenate two strings
% into one with a comma in between the two strings.
% The first string is represented by the character
% variable “str” and the second string is represented
% by the character variable “item”
%
output = [str, ‘,’, item];
return
%
% End of function mycat.
Next, define a function handle for mycat:
>> funhand = @mycat;
Finally, use this defined function handle in the second user defined function “fold.”
>> a = { ‘cow’ ‘cat’ ‘dog’ };
>> fold(a, funhand )
Unfortunately, this is where the MatLab documentation leave me hanging. I can’t discover the syntax for passing multiple input arguments to the function represented by the function handle, “funhand.” Maybe you can help me with this.
Example 2:
For the next level of complexity, define the function handle for the functionality of mycat from Example 1, but as an anonymous function:
>> funhand = @(str, item)[str, ‘,’, item];
As in Example 1, use the function handle in the second, user defined function “fold.”
>> a = { ‘cow’ ‘cat’ ‘dog’ };
>> fold(a, funhand)
As in Example 1, the MatLab documentation is not complete about the syntax for passing the arguments to and from “fold” and the function represented by the handle, “funhand.”
Example 3:
Now for a more concise syntax, there is no need to dedicate a separate line for defining the function handle for the anonymous function, it can be imbedded in the input arguments for the function “fold.”
>> a = { ‘cow’ ‘cat’ ‘dog’ };
>> fold(a, @(str, item)[str, ‘,’, item])
I am mildly confused by your use of the syntax in that the MatLab documentation shows no space between the closing parentheses of the input arguments and the leading square bracket of the function, whereas, you use a space.
Other than the important detail I mentioned above regarding variable passing, I understand the concept much better.
Oliver A. Chapman, PE
Oliver said:
> Unfortunately, this is where the MatLab documentation
> leave me hanging. I can’t discover the syntax for passing
> multiple input arguments to the function represented by
> the function handle, “funhand.” Maybe you can help me
> with this.
The Matlab documentation is pretty clear on this. Once you have a function handle you can call it just like any other function.
% As a normal function
function a = add(x, y)
a = x + y
end
>> fh = @add;
>> fh(1,2)
ans = 3
% or as an anonymous function
>> add = @(x,y) x + y;
>> add(1, 2)
ans = 3
Think about a function handle as a pointer to a function. I C/C++ you can do similar things with function pointers. Matlab function handles are easier to use and have more features than C function pointers.
Brad
Brad,
Thank you again. It is a bit more clear. From the documentation page for the function handle, I had read this section several times without understanding which set of arguments they were referring to:
The @ operator constructs a function handle for this function, and assigns the handle to the output variable sqr. As with any function handle, you execute the function associated with it by specifying the variable that contains the handle, followed by a comma-separated argument list in parentheses. The syntax is
fhandle(arg1, arg2, …, argN)
I infer from your posting that “arg1, arg2, … argN” are the input arguments for the function represented by the function handle, “fhandle.”
But, when I look at my Example 1, I can’t figure out what variable names to put in the argument list. Looking at your original example, when fold is called, “str” and “item” aren’t defined in the base workspace, they are only defined within the function workspace. When you generated the anonymous function handle within the call for “fold,” you specified these internal variables for the function handle to operate on. Therefore, you had to know all the internal details of the function “fold” before you could use the function handle.
A point of progress: I think I now see how this works when using a function handle in a MatLab provided function, like “fmindnd.” That function is limited to function handles representing functions with only one input argument, therefore my confusion regarding the input arguments doesn’t apply.
Your comments comparing this feature to C & C++ reinforce my perception that MatLab developers are ace C & C++ programmers. The OOP features of these languages are billed at allowing: 1. Packaging data and operations together. 2. Dividing problems into manageable pieces. 3. Promoting reuse of code. I have never worked on a project where 1 appeared to be an advantage and 2 & 3 are easy to implement in a Fortran type language using functions and subroutines. One of the great advantages of MatLab is that it was easy for me to engage with, from a Fortran perspective. It appears that some of these other features that I’m having trouble with are OOP type features and I’m having trouble getting the concepts.
Thanks again.
Oliver A. Chapman, PE
fh = @(str, item)[str, ‘,’, item]
str and item ARE the arguments to the anonymous function. They are not defined in any workspace.
>> fh(’XXX’, ‘YYY’)
ans =
‘XXX,YYY’
Thank-you for discussing some of these topics.
I have what may be a rather simple question, but does not seem to be discussed in the MATLAB documentation. I am running an optimization, where my function to be optimized is saved as a separate m-file. Something like:
[x,y] = fmincon(@myfun,x0,[],[],[],[],[],[],@funcon);
The problem is that I need to pass more than one variable to both myfun and to funcon, something like:
y = myfun(a,b,c,x)
As far as I can figure, when you call fmincon it only allows the variable x to be passed to @myfun. Is there any other way to pass a,b, and c to the function as well?
Thanks,
Silas
Silas,
How to do this depends on which version of MATLAB you’re using. If you’re using MATLAB 7.0 (R14) or later, define the variables a, b, and c before the FMINCON call and use an anonymous function:
a = 1; b = 2; c = 3;
x1 = fmincon(@(x) myfun(a, b, c, x), …)
You can use another anonymous function for funcon.
If you’re using a version of MATLAB prior to 7.0 (R14), you’ll need to do a little bit more work, since the input argument over which you’re trying to optimize is not the first input. The easiest way I can think of would be to write an inline function:
% Note the order of the inputs to the inline function.
% FMINCON optimizes over the first input of your objective
% function, so x needs to be the first input of the inline
% function.
%
% That’s the reason the anonymous function in the example
% above has x as its only input argument.
f = inline(’myfun(a, b, c, x)’, ‘x’, ‘a’, ‘b’, ‘c’);
Call FMINCON using this inline function as the first input and specify a, b, and c as additional parameters in FMINCON, after the options structure (the P1, P2, etc. inputs in the M-file help in versions prior to R14) just as described in this document from the Technical Support site:
http://www.mathworks.com/support/solutions/data/1-19HM6.html?solution=1-19HM6
Thanks, Steve,
That seemed to work just like you said it would. Now I just have to adjust my code so that everything converges in less than an hour!
-Silas
>> sin(’x')^2+cos(’x')^2
??? Function ’sin’ is not defined for values of class ‘char’.
Pepi-
You need to read the documentation. Perhaps x should be a sym. Or else numeric values.
–Loren