Running MATLAB scripts in batch mode

From NA-Wiki

Jump to: navigation, search

It can be useful to run MATLAB codes `offline` from the command line. The shell script mlbatch below allows you to do that.

#!/bin/sh
# Created by Henrik Holst    Mon, 25 Jan 2010 15:21:58 +0100
# Last changed: Henrik Holst Tue, 26 Jan 2010 10:58:01 +0100
CMD=""
while [ ! -z "$1" ]; do
	if [ x"$1" == x"-v" ]; then
		VERBOSE=1
	elif [ x"$1" == x"--verbose" ]; then
		VERBOSE=1
	else
		CMD="${CMD}${1/.m/};"
	fi
	shift
done
CMD="${CMD}quit"
LOGFILE="`mktemp -u -p . -t mlbatch-XXXXXXXXXX`.log"
DATE=`date +"%b %d %T"`
HOSTNAME="`hostname`"
HOSTNAME=${HOSTNAME%%.*}
PROGRAM=`basename $0`
echo ${DATE} ${HOSTNAME} ${PROGRAM}: logging to ${LOGFILE}
if [ $VERBOSE ]; then
	env matlab -nojvm -nodisplay -r "$CMD" | tail -n+11 | tee $LOGFILE
else
	env matlab -nojvm -nodisplay -r "$CMD" | tail -n+11 > $LOGFILE
fi

Use like this:

na56:matlab>mlbatch driver_omega3_evprob2d.m
Jan 25 16:53:33 na56 mlbatch: logging to ./mlbatch-hcyteGCOwp.log
na56:matlab>cat ./mlbatch-hcyteGCOwp.log
computing i=1 j=1
computing i=2 j=1
computing i=3 j=1
computing i=4 j=1
computing i=5 j=1
computing i=1 j=2
computing i=2 j=2
computing i=3 j=2
computing i=4 j=2
computing i=5 j=2
computing i=1 j=3
computing i=2 j=3
na56:matlab>

Add --verbose to run in verbose mode, i.e. show log on screen as the computation is being done. A word of warning: MATLAB does not flush its output. Because of this, you might have not see output immediately.

You can also run mlbatch with multiple MATLAB scripts like this:

na56:matlab>mlbatch driver_omega3_evprob1d.m driver_omega3_evprob2d.m driver_omega3_evprob3d.m
Personal tools