I am going to run a Matlab program in a remote Linux server using SSH. I was wondering how to run Matlab in Linux with only command line, which means there is no graphical envir
matlab -nodisplay
See here about -nodisplay.
Then -nodesktop
and -nosplash
are unnecessary. They don't make sense in text mode.
It's probably not a good idea to add -nojvm
unless you have a separate good reason to do so. Without the JVM, you lose some functionality whose absence might lead to confusion later on. Source: same link as above. On top of -nodisplay
, it doesn't make your non-graphical Matlab session any less graphical.
Here are a couple of ways to run commands non-interactively.
Way 1:
matlab -nodisplay < myScript.m
Put exit
as e.g. the last command in myScript.m
.
Way 2:
matlab -nodisplay -r "try, myFunction(); catch e, disp(getReport(e)), exit(7), end, exit()"
The second way is preferable, because e.g. if there is an error in the middle of the code, then the second way will print an error message and exit with a non-zero code. Whereas the first way is equivalent to typing the commands in directly, regardless of what Matlab says (which might be error messages).
In case the next question is "how to suppress the welcome message in text-mode Matlab?", it seems there is NO good way to get rid of it.
Depending of your need, an alternative is to do :
matlab -nosplash -nodesktop -wait -log -r "Matlab Script Line 1;Matlab Script Line 2;exit;"
It's the same method used by Azure DevOps Pipeline to log all Matlab Jobs Output to their online CLI Window.
Reference: Self-Hosted Windows Agent
Location: C:\agent\_work\_tasks\RunMATLABCommand_28fdff80-51b4-4b6e-83e1-cfcf3f3b25a6\0.2.15\bin\run_matlab_command.bat
The command is matlab -nodesktop
.
http://www.mathworks.de/help/techdoc/ref/matlabunix.html
Start MatLab with the following flags
matlab -nodesktop -nojvm -nosplash
-nodesktop
prevents the desktop
-nojvm
prevents starting of the java virtual machine
-nosplash
prevents the start-up splash screen.
Note, that, as Li-aung Yip noted in the comments, Mathworks does not recommend to use the -nojvm
flag.
Putting the other answers together plus some more error handling, save the following as an executable file matlab-headless
:
#/usr/bin/env bash
# restore the "sane" state of the terminal at the end
# otherwise interrupting the process may leave the terminal messed up
trap 'stty sane' EXIT
command="try, $1;, catch e, stack=getReport(e); fprintf(1, '%s\n', stack);, end, exit;"
# tail gets rid of the welcome message banner
matlab -nodisplay -nodesktop -nosplash -r "$command" | tail -n +11
Now you can run a Matlab command as:
matlab-headless "somecommand('bla', 42)"