This post is really for me as I managed to forget, misplace, or lose my notes on the last time I did this activity.

If you wish to run a matlab m-file from the command line or from a Makefile, here is the best way I’ve found to do it:

#!/bin/sh

# This version shows additional error output

script=`basename "$1" .m` # this will return $1 unless it ends with .m

if [ "$script" = "$1" ]; then

cmdterm=,

else

cmdterm=\;

fi;

shift # remove the first argument

args="$@"

argsq=`echo $args | tr '"' "'"`

matlab -nodisplay -r "disp('BEGIN>>'); try, $script $argsq $cmdterm catch me, fprintf(2,getReport(me)); exit(1); end, exit(0)" -nosplash | sed -e '1,/^BEGIN>>$/ d'

This extends the notes from the Informatics Bridging Team in a way to show information on the error.

Here are some quick examples with the example files at the matlabcmd gist

dgleich@recurrent:~/Dropbox/research/2013/06-18-matlab-command$ ./matlabcmd load_file.m mydata.txt

10

dgleich@recurrent:~/Dropbox/research/2013/06-18-matlab-command$ ./matlabcmd load_file mydata.txt

10

ans =

10

dgleich@recurrent:~/Dropbox/research/2013/06-18-matlab-command$ ./matlabcmd "randn(5)" # will display the output

ans =

0.5377 -1.3077 -1.3499 -0.2050 0.6715

1.8339 -0.4336 3.0349 -0.1241 -1.2075

-2.2588 0.3426 0.7254 1.4897 0.7172

0.8622 3.5784 -0.0631 1.4090 1.6302

0.3188 2.7694 0.7147 1.4172 0.4889

dgleich@recurrent:~/Dropbox/research/2013/06-18-matlab-command$ ./matlabcmd with_error.m # shows the error

Error using +

Matrix dimensions must agree.

Error in with_error (line 4)

c = a + b;

dgleich@recurrent:~/Dropbox/research/2013/06-18-matlab-command$ ./matlabcmd "randn(5) + randn(6)" # shows the error

Error using +

Matrix dimensions must agree.

Here’s a list of things that could make it better.

- Optional output — right now, this happens if you remove “.m” from the first file name, in which case it interprets your command as a matlab statement directly. In this case, we show the output with the “ans = ” intact.
- Error handling? I think it does a good job here, but I haven’t tested extensively.
- Others? Are there big issues with this command?
- Any better solutions out there already? (I looked briefly and didn’t find any!)

Advertisements