Run MATLAB script on cmd without opening the GUI window or the icon [duplicate] - matlab

I am running a MATLAB script from the Windows command prompt:
"C:\Program Files\MATLAB\R2014B\bin\matlab" -nodisplay -nosplash -nodesktop -wait -r "test.m"
The test.m is simple:
function test
disp('Hello!');
The output is displayed in the Matlab Command Window. Is there any way how I can force output to the windows prompt?

Use the command line option -log when you call Matlab from the command line (or any other shell or batch (e.g. cmd or bat) script).
It isn't documented as of Matlab 2017b, but it works.
Side note: -nodisplay isn't supported in the Windows version of Matlab, but if you want to prevent it from displaying figures, use -noFigureWindows instead.

Since R2019b, there is a new command line option, -batch, which redirects the output to the command line and handles other stuff for batch processing. See the documentation for Windows.
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.

I don't know of a way to do it in Windows to get Matlab to actually run in the DOS window which is what you would need for the display to be written in it. (FYI: You can in LINUX - but I assume you need to run in Windows).
For running in Matlab you have 2 alternatives that I can think of:
-logfile FILE on launch which will record all output to a FILE you specify - however how and when the file is written to disk is controlled by Matlab and I haven't tested to see - if your code doesn't do much it might only be written on Matlab exit.
diary FILE in your Matlab command, i.e. -r "diary FILE.TXT; test.m; diary OFF" - this is similar to above - but uses the diary function.
However you can get what you want if you can run your code compiled (I know thats a big if as you may not have the compiler - or if you regularly want to update test.m this is not the most efficient...
When you run a compiled code from a DOS prompt all the terminal messages are written to the DOS prompt. One thing I'd advise if this is suitable is to delete the "splash.png" file from your installation directory to avoid the splash screen displaying when you run from the DOS as its (probably) not needed.

I have found a solution at:
https://www.mathworks.com/matlabcentral/answers/91607-how-can-i-redirect-the-command-window-output-to-stdout-and-stderr-when-running-matlab-7-8-r2009a-i#answer_100958
I will replicate it here for convenience.
First I need to modify the matlab script to output to a text file:
function test
fid=fopen('output.txt','w');
fprintf(fid,'Hello!');
fclose(fid);
Then I should run the Matlab using a bat file with one additional command to display the contents of the output.txt:
"C:\Program Files\MATLAB\R2014B\bin\matlab" -nodisplay -nosplash -nodesktop -wait -r "test.m"
type output.txt
The type command will display the contents of 'output.txt' in the command window. So answer from #matlabgui was almost there. Thank you.
It is not a very elegant solution, but it works.

Related

bat file for running MATLAB code from Notepad++

I want to write a .bat file which, when I push the run button on Notepad++,
runs my matlab code through the command line
I wrote a simple batch file for running specific code (test.m)
How can I pass other file addresses through Notepad++'s run button to my batch file?
I would also appreciate other solutions.
My code:
"C:\Program Files\MATLAB\R2014b\bin\matlab.exe" -nodisplay -nosplash -nodesktop -r "; run('D:\test.m');"
This one I wouldn't use a CMD command, but rather a batch file that runs certain parts of your program. If I understand you correctly, then you want to run the MATLAB program when you click on the icon, as well as notepad++. What I would do is the following.
Right Click on the program, select properties, then change the target line to
"[Notepad++ Target Path Here]", "C:\Program Files\MATLAB\R2014b\bin\matlab.exe" -nodisplay -nosplash -nodesktop -r "; run('D:\test.m');"
This should run both programs
Hope this helps!

Force Matlab output to command line

I am running a MATLAB script from the Windows command prompt:
"C:\Program Files\MATLAB\R2014B\bin\matlab" -nodisplay -nosplash -nodesktop -wait -r "test.m"
The test.m is simple:
function test
disp('Hello!');
The output is displayed in the Matlab Command Window. Is there any way how I can force output to the windows prompt?
Use the command line option -log when you call Matlab from the command line (or any other shell or batch (e.g. cmd or bat) script).
It isn't documented as of Matlab 2017b, but it works.
Side note: -nodisplay isn't supported in the Windows version of Matlab, but if you want to prevent it from displaying figures, use -noFigureWindows instead.
Since R2019b, there is a new command line option, -batch, which redirects the output to the command line and handles other stuff for batch processing. See the documentation for Windows.
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.
I don't know of a way to do it in Windows to get Matlab to actually run in the DOS window which is what you would need for the display to be written in it. (FYI: You can in LINUX - but I assume you need to run in Windows).
For running in Matlab you have 2 alternatives that I can think of:
-logfile FILE on launch which will record all output to a FILE you specify - however how and when the file is written to disk is controlled by Matlab and I haven't tested to see - if your code doesn't do much it might only be written on Matlab exit.
diary FILE in your Matlab command, i.e. -r "diary FILE.TXT; test.m; diary OFF" - this is similar to above - but uses the diary function.
However you can get what you want if you can run your code compiled (I know thats a big if as you may not have the compiler - or if you regularly want to update test.m this is not the most efficient...
When you run a compiled code from a DOS prompt all the terminal messages are written to the DOS prompt. One thing I'd advise if this is suitable is to delete the "splash.png" file from your installation directory to avoid the splash screen displaying when you run from the DOS as its (probably) not needed.
I have found a solution at:
https://www.mathworks.com/matlabcentral/answers/91607-how-can-i-redirect-the-command-window-output-to-stdout-and-stderr-when-running-matlab-7-8-r2009a-i#answer_100958
I will replicate it here for convenience.
First I need to modify the matlab script to output to a text file:
function test
fid=fopen('output.txt','w');
fprintf(fid,'Hello!');
fclose(fid);
Then I should run the Matlab using a bat file with one additional command to display the contents of the output.txt:
"C:\Program Files\MATLAB\R2014B\bin\matlab" -nodisplay -nosplash -nodesktop -wait -r "test.m"
type output.txt
The type command will display the contents of 'output.txt' in the command window. So answer from #matlabgui was almost there. Thank you.
It is not a very elegant solution, but it works.

Matlab script call from command line first calls startup?

I have a startup Matlab script startup.m under
C:\SVN\myscripts\StartupScript
The script sets up paths and does some subsequent script calling successfully.
However, i created another file callMat.m in the same folder that just displays some data. When i run it from Matlab GUI, it works fine.
Howeever, calling it from cmd.exe,like below:
C:\Program Files\MATLAB\R2013b\bin\matlab.exe" -nosplash -nodesktop -wait -r "callMat"
I found that it opens Matlab command line and then
it first executes startup.m and then callMat.m .
Is this expected behavior, and if yes Why?
Thanks
sedy
Yes, this is expected behaviour. MATLAB executes startup.m when it starts up, whether it's started in the usual way, or whether it's started from the command line with -r and a command.
startup.m on your Matlab path is executed on startup.
I can find no description on the Matlab website suggesting that command line starting is any different.
In conclusion, it seems very likely this is expected behaviour. The documentation page here gives some suggestions as to the different places to put different options. In particular, it suggests that you:
Use startup.m to modify the default search path, predefine variables
in your workspace, or define defaults for graphics objects.

Writing log statements to standard output with Matlab

We're starting Matlab from our Jenkins buildserver. As the build may take some time it would be nice to get some log-outputs while matlab is running. Is there a way to print text to standard output? disp, fprintf and java.lang.System.out.printline only write to the matlab console, not to standard output.
Using a logfile or a pipe won't help, as Jenkins only reads from standard-output during a build step.
How can we write log-statements to the standard output while matlab is running?
EDIT:
We're running Matlab 2010b on Windows
Depending what you are doing with Matlab you could probably launch it in command line without GUI. I used this on a server and it behaves pretty much like a shell script and writes to standards outputs.
See the startup options.
I used the following:
/path/to/matlab -nojvm -nodisplay -nosplash -nodesktop -r /path/to/mfile
EDIT: forgot to mention one very important little detail, place an exit command at the end of your mfile or Matlab will hang there waiting.
It seems that the combination of -wait and -log (not -logfile) clones the command window output to the parent console's stdout, but only if you call the MATLAB executable in [MATLABROOT]\bin, not [MATLABROOT]\bin\win64 (the subdirectory for current arch).
Tested on Windows with R2015b and R2016b:
C:\MATLAB\bin\matlab.exe -wait -log
NOT
C:\MATLAB\win64\bin\matlab.exe -wait -log
Remember to put an exit/quit in your script if you are running with -r.
The only trouble is that I can't seem to find any documentation for the -log option! Meh.
There don't seem to be any good ways to do this from within MATLAB. The easiest way I can think of doing this is by using a shell script. You could write a small shell script which would simply print any input to stdout, and then call that shell script from within matlab using the unix (or system) commands. Jenkins should be able to read the command-line output of the script and work with that.
I figured out a way to do this and am also doing it for Jenkins Matlab interface on windows.
Basic idea is that you will use diary command, but then tail -f the file, but you need a smart way to kill the tail command if you open multiple matlab instances because there will be name collisions. So the method I'm using is to name the file log.txt where the PID used is MATLAB's PID it is using when it opens.
There is an undocumented feature in MATLAB that allows you to get its PID. So now, both your batch file and MATLAB know the PID without having to read/write to a random text file that will get messy when executing multiple jobs. So the PID you use that as your unique identifier. The PID of "tail -f" is also used by MATLAB to kill tail -f to make the batch file die and is found by MATLAB using the commandline details associated with the process invocation since it uses again the unique PID log file name.
This uses some wmic commands and needs Windows Vista/7 or above. With XP you probably have to work harder to get the process ID's but should be still possible.
Here is what to do:
1) Get gnu awk for windows: http://gnuwin32.sourceforge.net/packages/gawk.htm
2) Get tail.exe from windows resource kit: http://www.microsoft.com/en-us/download/details.aspx?id=17657
3) Make sure tail and awk are in your path (the windows resourece kit I don't think automatically puts them in the path)
3) Create a batch file called matlabrun.bat as follows, (note: you need the #echo off, also the entire command is quite long, scroll right..)
#echo off
wmic process call create "c:\matlab\bin\win64\matlab.exe -r \"cd('c:\jenkins\workspace\test'); workdir=pwd; outpath=[pwd '\output'] ; try; run('C:\MATLAB\work\test_run'); end; quit; \" " | findstr ProcessId | awk "{print $3}" | awk -F";" "{ print $1 }"
4) Create another batch file called run.bat with:
for /f %%i in ('matlabrun.bat') do (
echo MATLAB Log... > log%%i.txt
tail -f log%%i.txt
set logfilename=log%%i.txt
goto next
)
:next
del /f %logfilename%
5) The run.bat file will execute matlabrun.bat and since -wait is not passed, matlab will immediately return to the command line and execute the tail -f command. That will block the batch file from completing until you kill it. matlabrun.bat returns the PID of matlab.
6) Another important note: since you are using "wmic process create" which will provide you with a PID that MATLAB is using, but will default to a working directory of c:\windows\system32. So that is why I pass the work directory to matlab. wmic process create is also a bit particular about what parameters you put into your command string for matlab to run. So it appears to have a problem with using commas in your command string. So I suggest not to use those, or figure out how to escape them (it might be that ^, works, but I just removed my commas anyway in my matlab run command).
6) The "test_run.m" file contains the following code to write to the correct log file and to kill correct tail -f instance.
matlabpid=feature('getpid');
filename=['log',num2str(matlabpid),'.txt'];
filenamefull=[workdir,'\',filename];
diary(filenamefull);
disp('Script starting...')
%%% put your code here %%%
disp('Script completed...');
diary off;
%%% FIND PID of tail.exe and kill it
%%% by using the name of the log file in the process command line
[a,b]=dos(['wmic process get Commandline,ProcessId']);
C=textscan(b,'%s','delimiter','\n');C=C{1};
for jj=1:size(C,1),
if strfind(C{jj},filename),
D=textscan(C{jj},'%s');D=D{1};
dos(['taskkill /f /pid ',D{4}]) %kills tail.exe which is the log watcher
break
end
end
7) You start it by doing run.bat. It will go and execute matlab, then start tailing the output while MATLAB runs in real-time. Then when done it will delete the log file.
8) My directory structure / files are in these locations (I'm using win7 64bit):
c:\jenkins\workspace\test\tail.exe
c:\jenkins\workspace\test\awk.exe
c:\jenkins\workspace\test\matlabrun.bat
c:\jenkins\workspace\test\run.bat
c:\matlab\work\test_run.m
c:\matlab\bin\win64\matlab.exe
If you are using 32bit matlab, point it to the win32 directory. To get the correct PID, you need to specify the actualy matlab.exe binary in the win32 or win64 directory.
You can do this by pointing the -logfile option to the Jenkins log file. Something like the following:
"C:\path\to\matlab.exe" "-r" "functionToRun" "-logfile" "%JENKINS_HOME%\jobs\%JOB_NAME%\builds\%BUILD_NUMBER%\log" /wait
You can use the diary mode. Not sure if it will fit your specific implementation.
http://www.mathworks.com/help/techdoc/ref/diary.html
I didn't find a real solution. Mathworks created some wrapper tool. But this will only output the results after matlab has exited. You won't get any ouput during execution.
http://www.mathworks.de/support/solutions/en/data/1-ACT3YN/index.html?product=ML&solution=1-ACT3YN
So I'll have live without real live-output...
Or try using '-logfile' option in matlab.
matlab.exe -nodisplay -nosplash -nodesktop -wait -logfile logfile.txt -r "try script.m ;catch err; disp(err.message); end ; exit"
I prefer using bash (Execute shell) in Jenkins, then you can tail the log-file while matlab is running.
matlab.exe <...> &
matpid=$!
tail -f logfile.txt &
tailpid=$!
wait $matpid
matexit=$?
kill $tailpid
sleep 1 # Just to make sure kill is done before Jenkins step ends and no zombie processes
exit $matexit

Run a MATLAB script from Windows DOS prompt

I am trying to run a Matlab script from Windows command prompt but I can't execute it sometimes. The script runs fine when manually launched. Matlab version is 2011a and Windows is Server 2003 SP2. Details:
Script mytask.m is located inside say E:\Production\Project. This is SAVED on Matlab's path.
When I place mytask.m inside bin folder, it executes fine by the command:
`C:\Program Files\MATLAB\R2011a\bin>matlab -r mytask`
If you delete it and try to access it at its original location, the script doesn't run although Matlab editor window is launched:
`C:\Program Files\MATLAB\R2011a\bin>matlab -r "E:\Production\Project\mytask"
Any suggestions please? Thanks.
The syntax for matlab -r is
matlab -r "statement"
In other words, you need to provide some executable commands as the statement. For example:
matlab -r "run E:\Production\Project\mytask"
However, it seems that matlab does not load the customized paths in this way. If you have some customized paths, you probably have to define them in startup.m and place this startup.m in the directory where you invoke matlab.
I didn't check myself, but if you define E:\Production\Project\ as the path in startup.m, you probably can run matlab -r mytask without problem, as mytask will be recognized as a user function/script.
A simple example of startup.m
path(path, 'E:\Production\Project\');