Like: MATLAB script that can get arguments from Unix command line

Just for 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 

Now I can run this script, and pass arguments to it from the Unix command line , for example:

 % python add_em 3 8 11 

If I create a 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 runs just like the script does? In particular, it should be able to read its arguments from the Unix command line (unlike, for example, the MATLAB GUI command line) and print their numerical sum to standard output.

NOTE: this script should not be "standalone"; IOW, we can assume that MATLAB is locally installed, and even at the command line you can specify matlab (similar to the first form above, where the python interpreter is explicitly called on the command line).

Thanks!

PS: Needless to say, this script is the antithesis of "reliable", but my goal was to prepare an easily conveyed example.

+7
source share
1 answer

You may have a MATLAB function that does what you want inside add_em.m

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

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

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

Options - suppress the desktop, java and splash, so the script / function will execute without additional overhead.

You can optionally suppress the welcome / copyright message MATLAB by redirecting the output to a log file (for any calculations) or ending, for example, the output to get something printed on the terminal

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

Update . Just found out about this post / replies with related information: suppress the initial Matlab message

+8
source

All Articles