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 thepython
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With