EE/CS @ The Cooper Union
On Mon Apr 19 2021 16:44:39 GMT-0400 (Eastern Daylight Time)
Return to blog
I felt compelled to write about this because I couldn't figure this out on my own in the three years of using MATLAB.
In the MATLAB examples, you'll often see something along the lines of:
clc; clear; close all; t = 1:10; x = t.^2; y = sin(t); figure; hold on; plot(t, x); plot(t, y); hold off; grid on;
(This particular example is nonsense -- don't run it.)
This has always left me wondering: what the heck is
hold on, or
grid on, in terms of the grammar of MATLAB? Are they functions? Special keywords? Some sort of functor-like object? It makes me insecure in the same way as Ruby or Groovy made me feel with optional parentheses -- but this was easily resolved by looking up something along the lines of "Ruby optional parentheses." A Google search for "MATLAB optional parentheses" doesn't even bring up the correct term for this phenomenon on the first search page (first ten results): "command syntax."
It turns out the above example is exactly equivalent to:
clc(); clear(); close('all'); t = 1:10; x = t.^2; y = sin(t); figure(); hold('on'); plot(t, x); plot(t, y); hold('off'); grid('on');
After looking at the transformed output, the basic rule should be fairly easy to tell. This "command syntax" is the same as a function call, where the arguments are space-delimited (rather than comma-delimited), and are passed in as character arrays.
It's important to note that the parameters are always converted to character arrays before the function invocation, so
grid 'on' and
grid on are equivalent. Another result of this is that command syntax doesn't work with named symbols:
stem x will result in
stem('x'), which is (probably) not what you intend to compute.
Another potential complication is that this can introduce grammatical ambiguities. The example stated in the documentation is
ls ./a: if it is unknown whether
ls is a function (in which this would mean the function call
ls('./a')) or a variable (in which this would mean the elementwise division
ls ./ a), then MATLAB has to do some guessing.
See the documentation page for more details.
1. If I've learned anything from the compilers course, it's that optional or multi-branching parts of a grammar are really annoying to deal with, thus further promoting the superiority of LISP's LL(1) grammar.
© Copyright 2021 Jonathan Lam