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?
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;"
Here is what I would use instead, to gracefully handle errors from the script:
If you want more verbosity:
I found the original reference here.
And I use Ubuntu
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');"
Here are the steps:
cd C:\M1\M2\M3
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.Thanks to malat. Your comment helped me. But I want to add my try-catch block, as I found the
MExeption
methodgetReport()
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.
For a false model name passed to legacy code generation method, the output would look like:
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 commandtype logfile.txt