How to submit MATLAB jobs as batch jobs to Slurm

Using MATLAB as a batch job through Slurm isn't all that hard. This simple how-to shows you how to do it. Please note that this how-to covers serial MATLAB jobs only. Running parallel MATLAB jobs through Slurm is also possible, but is a bit more complicated. I hope to document how to do that in the future. First, let's simplify the problem and look at how to run a MATLAB script from the command-line. We'll begin by creating a very simple MATLAB script with only a couple of MATLAB commands, and save it to the file name 'add.m'
[pbisbal@sunfire09 matlab]$ cat add.m
a = 1;
b = 2;
c = a + b;
disp(c);
Now we can run MATLAB using this script as batch job on the command-line like this:
[pbisbal@sunfire09 matlab]$ matlab -nodisplay -nojvm < add.m

< M A T L A B (R) >
Copyright 1984-2017 The MathWorks, Inc.
R2017a (9.2.0.556344) 64-bit (glnxa64)
March 27, 2017


For online documentation, see http://www.mathworks.com/support
For product information, visit www.mathworks.com.

>> >> >> >>      3

>> >>
Please note that in the above matlab command, I used shell redirection with the "<" character to redirect the contents of the file add.m to the standard input of the matlab command, and I used the two switches "-nodisplay -nojvm". "-nodisplay" tells MATLAB not to start the GUI interface, which is unnecessary for a batch job. The "-nojvm" switch tells MATLAB not to start the Java virtual machine (JVM). If you know your job needs to use the JVM, you should omit the "-nojvm" flag. Now to submit that command as a batch job to slurm, create a simple sbatch script:
[pbisbal@sunfire09 matlab]$ cat matlab.sbatch
#!/bin/bash

#SBATCH -n 1
#SBATCH -p ellis
#SBATCH -t 00:05:00
#SBATCH -J matlab_demo
#SBATCH -o matlab_demo-%j.out
#SBATCH -e matlab_demo-%j.err
#SBATCH --export=ALL

module load matlab/r2017a

matlab -nodisplay -nojvm < add.m
And now submit it to slurm using the sbatch command:
[pbisbal@sunfire09 matlab]$ sbatch matlab.sbatch
Submitted batch job 225551
When it completes, check the output:
[pbisbal@sunfire09 matlab]$ cat matlab_demo-225551.out

< M A T L A B (R) >
Copyright 1984-2017 The MathWorks, Inc.
R2017a (9.2.0.556344) 64-bit (glnxa64)
March 27, 2017


For online documentation, see http://www.mathworks.com/support
For product information, visit www.mathworks.com.

>> >> >> >>      3

>> >> 
That's it! That's all there is to running MATLAB as a batch job through Slurm.