Run a MATLAB function/script with parameters/arguments from the command line

Here’s how to run a MATLAB function with parameters from the command line.

> matlab -r "littleFunction batman superman"

where littleFunction is the name of your MATLAB file (i.e. littleFunction.m) and batman is the first parameter and superman is the second parameter. Note the quotes around the function name and the parameters! Note that the function name does NOT include the “*.m” extension.

If you need a bit more of an example, read on…

First we create a little function with two parameters.

%%%%%%
% Create a function.
function littleFunction(parameterA, parameterB)
 
display(parameterA);
display(parameterB);
 
% Uncomment this to exit MATLAB when complete.
%exit;

Note that little exit; at the end can be used if you want to close MATLAB immediately when it reaches the end of your code.

Then we navigate to the directory where littleFunction lives, and from the command line we type,

> matlab -r "littleFunction batman superman"

When we run command, MATLAB will start and run this function. You will see batman and superman being displayed.

parameterA =
 
batman
 
parameterB =
 
superman

And you’re done!

Questions/comments? If you just want to say thanks, consider sharing this article or following me on Twitter!