How to run the m-file? After the m-file is saved with the name filename. m in the current MATLAB folder or directory, you can execute the commands in the m-file by simply typing filename at the MATLAB command window prompt.
Type the script name on the command line and press Enter. For example, to run the numGenerator. m script, type numGenerator . On the Editor tab, click the Run button.
To run a MATLAB script from the the command line, use MATLAB's -r option, as in this example which runs the Matlab script my_simulation. m from the current directory. Note that the MATLAB script that you run should have an exit command in it.
if name. m exist in the same directory and if you want to call this file in name2. m, then just type 'name;' inside name2. m, no extension is needed!
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;"
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:
"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:
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.
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.
cat 1.m | matlab -nodesktop -nosplash
And I use Ubuntu
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With