127

Suppose that;

I have an m-file at location:
C:\M1\M2\M3\mfile.m

And exe file of the matlab is at this location:
C:\E1\E2\E3\matlab.exe

I want to run this m-file with Matlab, from command-line, for example inside a .bat file. How can I do this, is there a way to do it?

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
hkBattousai
  • 10,583
  • 18
  • 76
  • 124
  • 1
    you might find these useful: http://stackoverflow.com/questions/14495/how-can-i-stop-matlab-from-returning-until-after-a-command-line-script-completes, http://stackoverflow.com/questions/1857825/run-matlab-in-batch-mode – Amro Jul 11 '11 at 23:02

11 Answers11

128

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

Giovanni Mascellani
  • 1,218
  • 2
  • 11
  • 26
hkBattousai
  • 10,583
  • 18
  • 76
  • 124
72

I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open. Therefore, to the answer of @hkBattousai I will add the exit command:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"

e.nikolov
  • 127
  • 1
  • 11
elachell
  • 2,527
  • 1
  • 26
  • 25
  • 7
    For some reason if `mfile.m` triggers an error the explicit `exit` function is never called, making the whole process wait... – malat Sep 14 '15 at 15:39
46

Here is what I would use instead, to gracefully handle errors from the script:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\<a long path here>\mfile.m'), catch, exit, end, exit"

If you want more verbosity:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\<a long path here>\mfile.m'), catch me, fprintf('%s / %s\n',me.identifier,me.message), end, exit"

I found the original reference here. Since original link is now gone, here is the link to an alternate newreader still alive today:

malat
  • 12,152
  • 13
  • 89
  • 158
29

On Linux you can do the same and you can actually send back to the shell a custom error code, like the following:

#!/bin/bash
matlab -nodisplay -nojvm -nosplash -nodesktop -r \ 
      "try, run('/foo/bar/my_script.m'), catch, exit(1), end, exit(0);"
echo "matlab exit code: $?"

it prints matlab exit code: 1 if the script throws an exception, matlab exit code: 0 otherwise.

slux83
  • 686
  • 9
  • 20
  • 3
    To display the error as MATLAB would do when not catching it, just do `"try, run('/foo/bar/my_script.m'), catch e, disp(getReport(e)), exit(1), end, exit(0);"` – danieleds Nov 29 '18 at 15:26
18

Since R2019b, there is a new command line option, -batch. It replaces -r, which is no longer recommended. It also unifies the syntax across platforms. See for example the documentation for Windows, for the other platforms the description is identical.

matlab -batch "statement to run"

This starts MATLAB without the desktop or splash screen, logs all output to stdout and stderr, exits automatically when the statement completes, and provides an exit code reporting success or error.

It is thus no longer necessary to use try/catch around the code to run, and it is no longer necessary to add an exit statement.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • This seems to work well most of the time, but running `matlab -batch "disp('hello')"` on Windows with R2021b prints "hello" and then a Java error `Caused by: com.mathworks.util.ShutdownRuntimeException: Java is shutting down`. – Paul Wintz Feb 02 '22 at 19:58
  • @PaulWintz That sounds like something you should report as a bug to the MathWorks. You can probably circumvent that with `matlab -nojvm -batch "..."`, so that the Java VM is never started. – Cris Luengo Feb 02 '22 at 20:22
  • @Chis Luengo, including `-nojvm` does prevent the error. Thanks! – Paul Wintz Feb 02 '22 at 20:46
15

Here are the steps:

  1. Start the command line.
  2. Enter the folder containing the .m file with cd C:\M1\M2\M3
  3. Run the following: C:\E1\E2\E3\matlab.exe -r mfile

Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r option tries to start the given .m file as soon as startup occurs.

aardvarkk
  • 14,955
  • 7
  • 67
  • 96
  • 1
    It won't run inside a .bat file. I gave it as an example. Actually, I will run it by the Win32 API function `CreateProcessW()`. – hkBattousai Jul 13 '11 at 09:01
13
cat 1.m | matlab -nodesktop -nosplash

And I use Ubuntu

zx485
  • 28,498
  • 28
  • 50
  • 59
Jia Ruipeng
  • 141
  • 1
  • 3
8

Thanks to malat. Your comment helped me. But I want to add my try-catch block, as I found the MExeption method getReport() that returns the whole error message and prints it to the matlab console.

Additionally I printed the filename as this compilation is part of a batch script that calls matlab.

try
    some_code
    ...
catch message
    display(['ERROR in file: ' message.stack.file])
    display(['ERROR: ' getReport(message)])
end;

For a false model name passed to legacy code generation method, the output would look like:

ERROR in file: C:\..\..\..
ERROR: Undefined function or variable 'modelname'.

Error in sub-m-file (line 63)
legacy_code( 'slblock_generate', specs, modelname);

Error in m-file (line 11)
sub-m-file

Error in run (line 63)
evalin('caller', [script ';']);

Finally, to display the output at the windows command prompt window, just log the matlab console to a file with -logfile logfile.txt (use additionally -wait) and call the batch command type logfile.txt

Community
  • 1
  • 1
CanO
  • 111
  • 1
  • 4
3

I run this command within a bash script, in particular to submit SGE jobs and batch process things:

/Path_to_matlab -nodisplay -nosplash -nodesktop < m_file.m
Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
LMLacerda
  • 31
  • 3
1

Since none of the answers has information about feeding input argument, it is important to add it here. After some research, I found this link

Feeding the arguments is very similar to how we run a Matlab function.

matlab -r 'try myfunction(argument1,argument2); catch; end; quit'

If you are somehow getting an argument from bash/terminal, you simply need to insert that into the bash command as:

matlab -r 'try myfunction($MY_BASH_ARG,argument2); catch; end; quit'

(This is after a couple of trial and error)

smttsp
  • 4,011
  • 3
  • 33
  • 62
  • You can use `matlab -r "addpath('/my/mfile/directory/'); my_mfilename(argument1, argument2)"` so you don't have to rely on the working directory which can be reset by `startup.m` – J. Rehbein Feb 11 '21 at 21:31
0

In the new releases of matlab, there is no need to specify the option "-nodisplay" in the command line mentioned by the accepted answer. Simply doing the following will work without any warning:

"C:\...\matlab.exe" -nosplash -nodesktop -r "run('<matlab-script>.m'); exit;"
Rebel
  • 472
  • 8
  • 25
  • 1
    In the new releases, use the `-batch` option, `-r` is no longer recommended. https://stackoverflow.com/a/58358304/7328782 – Cris Luengo Aug 26 '23 at 04:27