Monthly Archives: August 2016

Passing arguments to a Matlab script

It’s sometimes useful to run the same program with different parameters many times, for example when we want to systematically vary a parameter in a model to see how it affects the behavior of the model. This is really easy in C and related languages, which have excellent command-line processing facilities. It turns out to be easy in Matlab as well. Since I had to hunt around to figure out how to make this trick work, I thought I would present it here.

Matlab has a -r command-line switch that allows you to execute a Matlab command right after Matlab starts up. For example, here is a Matlab command-line version of the classic “Hello, world!” program:

matlab -r "disp('Hello, world.')"

(As a parenthetical remark, the mysteries of bash command-line interpretation defeated my attempts to put an exclamation mark at the end of the sentence, as is traditional.) If you type this command at a shell prompt, Matlab will print “Hello, world.” just before the Matlab command-line prompt appears. You can of course imagine initializing one or more variables in similar manner:

matlab -r "x=1; y=2;"

OK, but what if you want to initialize some variables used by a Matlab program? There are a couple of options here. One is to include the program name in the quoted command string. If your program is called prog.m, for example, you could type

matlab -r "x=1; y=2; prog"

Alternatively, you could redirect standard input:

matlab -r "x=1; y=2;" < prog.m

The above will work provided the variables x and y are not defined inside prog.m. If you always want to define these variables from the command-line, then that’s fine. However, you might want to have variables that have default values that you can override from the command line. This is also fairly easy. Consider the following program, which we will assume has been saved into a file called prog2.m:

if ~exist('x')
    x = 0.1;

The command line matlab -r "x=1; prog2" displays an x value of 1, while the command line matlab -r prog2 sets x to 0.1, as you might have expected.