Alexanov
Alexanov

Reputation: 125

How can I run Matlab .m file repetitive in background?

I have project that was wrote in MATLAB. It has Main file like Main.m, I want to run Main.m repetitive every 1 Second in background. I don't want to see any display and opening windows from MATLAB. How can I do this ?

Upvotes: 0

Views: 1149

Answers (2)

Emrah Diril
Emrah Diril

Reputation: 1755

Assuming there is a top-level function in Main.m that you would like to execute once every 1 second, one possibility is to start an instance of Matlab and create another script that calls your function in a forever loop with a 1 second pause (making sure that this other script has Main.m file in the PATH so it can see it)

function run_main_forever() while true my_function() pause(1) end end

You can have a .bat file start matlab in the background and run the script like this:

matlab -nodesktop -nosplash -r "cd('C:\Path\To\'); run_main_forever();"

See this link for further details on launching MATLAB without the desktop: https://blogs.mathworks.com/community/2010/02/22/launching-matlab-without-the-desktop/

Upvotes: 1

Daniel
Daniel

Reputation: 36710

There are two steps to achieve this. First write some m script which calls your Main function every 1s. You can use a loop like this one. Getting the time via toc is important in case your main function takes some time to compute. An alternative are timers, which avoid any time drift (The loop is typically slightly above 1s, the timer will be 1s on average).

Once your MATLAB knows what to do, the question is who to start it. There is the -batch option:

Execute MATLAB script, statement, or function non-interactively. MATLAB:

  • Starts without the desktop
  • Does not display the splash screen
  • Executes statement
  • Disables changes to preferences
  • Disables toolbox caching
  • Logs text to stdout and stderr
  • Does not display dialog boxes

Exits automatically with exit code 0 if script executes successfully. Otherwise, MATLAB terminates with a non-zero exit code.

statement is MATLAB code enclosed in double quotation marks. If statement is the name of a MATLAB function or script, do not specify the file extension. Any required file must be on the MATLAB search path or in the startup folder.

Use the -batch option in non-interactive scripting or command line work flows. Do not use this option with the -r option.

To test if a session of MATLAB is running in batch mode, call the batchStartupOptionUsed function.

Example: -batch "myscript"

This means MATLAB will not open any window, instead you see any output in the calling command line. How it looks on LINUX:

x@y ~ $ matlab -batch "1+1"

ans =

     2

Upvotes: 2

Related Questions