Loren on the Art of MATLAB

Duality Between Function and Command Syntax

A long time ago, I covered the topic of the duality between command and function syntax.

Contents

What is Command-Function Duality?

For calling functions with only literal string input values, i.e., strings delimited by the usual single quote ('), you can avoid the overhead of using parentheses and comma separators to invoke the function, especially if you want either no output or only one output. Let me show you an example.

Checking Directory Contents

Suppose I want to see the MATLAB code files in my directory beginning with the letter 'q'. Here are three ways to do such a query.

First way:

dir q*.m

qichen31.m  quadvec.m   quantum.m



Second Way:

dir('q*.m')

qichen31.m  quadvec.m   quantum.m



Third Way:

out = dir('q*.m')

out =
3x1 struct array with fields:
name
date
bytes
isdir
datenum


Discussion of Results

From these three methods, you can see that the first two give the same output, a list of the names of matching files. When using the command syntax (the first way), you can't store the output in a named variable. In this case, the decision was to print something out in a useful format, but not to place the information into a variable for further programmatic use.

The second result is equivalent to the first. You can see the duality looking at these two statements. The first and second are equivalent. Simply replace the space and following string (or strings) into a comma-separated list of the same string(s) inside parentheses. This means that the statement myfun A B c is equivalent myfun('A','B','c').

And now for the third statement. Clearly it is different than the first two. First, you can see that something is returned in the output variable out. Second, you can see that out is not simply a list of names, but a struct containing several fields with information, including name, date, etc.

Default MATLAB Behavior

MATLAB functions often return at least one output, even if the user does not supply an output variable. If the function does return an output when the user does not specify one, the result goes into a variable named ans.

Overriding Default Behavior

It is possible to override default behavior for your function outputs. To do so, we take advantage of the function nargout. This function allows us to query how many output variables the function is called with. In the case of the function dir, you can imagine the logic of the code goes something like this:

1. check nargout
2. if nargout is 0, get and print the list of matching files/directories
3. if nargout is greater than 0, collect the relevant directory information and place it into a structure

With the command form for calling a MATLAB function, the value for nargout is 0. Despite this, some functions are designed to return a value, though without a specified output, ans is created or updated.

Do you take advantage of command-function duality? In functions you create? At the MATLAB prompt or in application code your write? Let me know here.

Get the MATLAB code

Published with MATLAB® R2013a

4 Responses to “Duality Between Function and Command Syntax”

1. Andris Vaivads replied on :

This is an excellent feature but why it does not work for package functions? For example, if

>> func1 arg1 arg2

is ok, then if func1 is part of a package ‘+test/’ then

>> test.func1 arg1 arg2

gives error. Where is logic?

2. Daniel Shub replied on :

I avoid the command syntax religiously in my functions. From the command line sometimes I use the command line version of functions like edit, doc, clear for convenience. I would gladly give up the command line version if MATLAB would treat the oddly spaced x ==0, the same as x==0, x == 0, and the oddly spaced x== 0. Programming languages, especially ones that allow you to generally use whitespace freely, should not have crazy whitespace dependencies.

You mentioned overhead of the parenthesis and comma separators. Is the commandline interface faster? I would have thought it would have been slower.

3. Loren Shure replied on :

Hi Andris-

You can work around this by importing the package first. Command form is meant to be a convenience so would fit well with importing.

Hi Daniel-

I too avoid command syntax in functions usually – because I don’t want output to show up that I might depend upon. Exceptions are cases of functions with no outputs, such as when I use something like

hold all

Command-line interface should have no speed impact if the function has no outputs and we can compare the 2 forms fairly.

–Loren

4. Julian replied on :

I do like the command form, but was not aware of the problem pointed by Daniel, with x ==0 erroring when x == 0 is OK! Surely this is a problem TMW must address? cos (pi ()) returns -1 fine, although allowing space between a function name and its leading parenthesis, while disallowing space before a binary == operator does not seem quite right to me!

The command form often saves the typing of brackets and/or quotes, which, as SHIFT-key-combos are, for me, slower to type. In fact I sometimes code for command input to my functions to parse char inputs into numerics. Reading this blog entry I was motivated to post this rather trivial entry on the file-exchange http://www.mathworks.com/matlabcentral/fileexchange/41934.

How about when one tab-completes a function name in the command window, a pair of () parentheses is automatically added with the insertion point between them while such brackets removed at once by typing a single space? Could this help make the function() form a little easier to use? When I have used the NetBeans IDE it always pairs quotes and parentheses, leaving the insertion point between these. I think Excel helps similarly with the formulae brackets .

Loren Shure works on design of the MATLAB language at MathWorks. She writes here about once a week on MATLAB programming and related topics.

These postings are the author's and don't necessarily represent the opinions of MathWorks.