Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How : MATLAB script that can get arguments from Unix command-line

Just for the sake of concreteness, consider the following super-simple Python script, in a file called add_em:

#!/usr/bin/env python
# script name: add_em

from sys import argv

x = int(argv[1])
y = int(argv[2])
x_plus_y = x + y
print '%d' % x_plus_y

I can now run this script, and pass arguments to it, from the Unix command line, like this:

% python add_em 3 8
11

If I make the script executable, I don't even need to mention python on the command line:

% chmod +x add_em
% add_em 41 -29
12

Can someone show me how to write (and run) a MATLAB script so that it performs exactly like the script above does? In particular, it must be able to read its arguments from the Unix command line (as opposed to, e.g., the MATLAB GUI's "command line"), and print their numerical sum to standard output.

NOTE: this script need not be "stand-alone"; IOW, one may assume that MATLAB is locally installed, and even that one can mention matlab in the command line (analogously to the first form above, where the python interpreter is explicitly invoked on the command line).

Thanks!

PS: Needless to say, this script is the antithesis of "robust", but my aim was to produce a readily conveyed example.

like image 385
kjo Avatar asked Aug 31 '12 22:08

kjo


1 Answers

You can have a MATLAB function doing what you want inside add_em.m

function add_em(x, y)
x_plus_y = x + y;
disp(x_plus_y);
exit;

and then call it from Unix command line using the -r switch. Example:

matlab -nodesktop -nojvm -nosplash -r "add_em(3, 8)" 

The - options suppress desktop, java and splash so the script/function will be executed without additional overhead.

You can additionally suppress the MATLAB welcome/copyright message by redirecting output to a logfile (for any computations) or tailing, for example, the output in order to get something printed on terminal

matlab -nosplash -nodesktop -nojvm -r "add_em(3, 8)" | tail -n 3

Update: Just found out this post/answers with relevant info: suppress start message of Matlab

like image 189
gevang Avatar answered Sep 22 '22 08:09

gevang