matlab compiled program execute code on close - matlab

I have a compiled matlab program that runs as a dos box basically (ie no GUI). Is there a way to get code to execute when someone closes the program? Specifically closing by clicking on the X?

I suggest to define a cleanup task. This will be executed whenever a function is terminated (by whatever means), so as long as closing the program is not done with a kill -9 command or similar, the code is being run.

Related

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 ?
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
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/

waitbar matlab before start a standalone script

I did a standalone application in Matlab and it works. The only problem is that when I launch the application, it takes time before start asking to the user some file (it is the first think the program has to do). The user does not understand if the program is working or not, since no message neither symbol of working progress appear on the screen.
My idea is to show a waitbar until the window asking the file to user appears.
How can I do this? is it possible to use the waitbar outside a loop?
The script starts as follow:
close all
clear all
[filename,pathname] = uigetfile({'*.xlsx'},'Opening File','C:\');
I don't know why, it takes time before open the window for choosing the file.
The time between launch and file selection input appearing is most likely due to the time it takes to load the MCR. You could add a splash screen to your compilation.
If the end user is running from a command line wrap your exe in a system/shell which writes to the command window that the application is starting.
Your issue is most likely the use of clear all. This makes MATLAB remove all variables (in scope, global and persistent), and compiled scripts from memory, forcing it to recompile and load everything again.
If your purpose is to clear all variables in the current scope, you should be able to increase the initial speed of your script by only running clear instead.
Even faster speed can be achieved if you specify which variables to clear using clear var1 var2 ...

MATLAB code break

I have started running a script on MATLAB that takes days to finish. Usually, if I changed my mind and I don't want wait for it to finish and I get content with the intermediate results, I highlight the command window and press Ctrl-C to break the code.
Now, I have run MATLAB. But its desktop got kinda stuck in the background. When I try to restore the desktop from the toolbar, it does not restore. But I know from the task manager that the process is running and is consuming Memory and CPU performance. So, I am kinda stuck. I don't want to kill the process because I need the intermediate values in the workspace, and I can't open the desktop to break the code using ctrl-c.
Is there any solution? For example, is there any command that can be used in the command prompt to act as ctrl-c for MATLAB?
I am using MATLAB R2012b and Windows 8.
Quick try to fix the recent Problem:
Try ty set a higher priority to matlab.exe in the Task Manager. (Right click -> Priority -> Higher than normal). Then see if you can get the window to front.
Some approaches to avoid this problem in future:
Try to optimize your code. For starters look at: http://de.mathworks.com/help/matlab/matlab_prog/vectorization.html
Use Matlab compiler for faster execution: http://de.mathworks.com/products/compiler/
Include some drawnow commands at stratetic positions in the code. This allows matlab to process the Event Queue and capture ctr-C commands.
Save intermediate results to output files. For example you could write an output file all 30 min with your intermediate results. Easyiest way would be just save(filename). Then a .matfile with all your workspace variables is generated. You can than kill the process in the task manager, without loosing too much results.

How to return to prompt after running an exe file compiled with mcc (Matlab compiler)

I have an executable created with mcc. The .m file has a simple function that reads and plots values. After I run it from DOS, it freeze without returning execution to DOS. 2 questions:
1) How can i return execution to dos? I tried "return" and "exit" commands but didnt help
2) How to close the dos windows? is the only way to use a batch file or can I do it with a command in the .m file?
thanks
A.
There are 2 scenarii:
If your run your matlab executable from a DOS window, the DOS window will not get control back until the program terminates. If the program generate matlab figures (plot, surf, etc...), the program will not return to the console until all of the figures are closed.
You may think it is a waste for a simple plot, but after all your figure could be a evolved gui with a lot of code to execute. Or even a simple figure with a closeRequestFcn. So in Matlab terms, your program may still have instructions to execute as long as a figure is opened, so it will not return until it sure there is nothing more to do.
If you simply double clicked on your executable, the DOS looking console which open with your program will have the same behaviour. It will not disappear until the program returns (so until all your figures are closed if relevant).
I am not sure about linux, versions, but if you are running on windows, there is a way to suppress the DOS looking console for your graphic applications. Look at the -e switch in the mcc options.
This switch will compile your program in a way that no DOS console is opened when you double click on your executable.
So to summarize, I would recommend:
If your program is a 'command line' type (a function that takes input from the console and return values to the same). => Compile with normal options, and execute it from a DOS window (you do not want the window to disapear as soon as the program terminates.)
If your program is a gui or even simple plotting functions, with no need for console interactions, then compile with the -e switch and execute it by double clicking the .exe file.
note that in case you use the -e switch, it is recommended to direct potential output to a logfile. Look at the mcc documentation for more info.
edit
If you really need the DOS console and some graphic output, run your program form the command window with the following syntax:
start /b YourProgram
This will start the program in "background mode" (use YourProgram & in Linux terminal). You will be able to do anything in this console window, and you will also see the output from your matlab executable.
It can be confusing because the output from your program will be added to the simple dos prompt and you may think you do not have the control but if you type any command it will work. You can even start many program this way and retain control in your console, but all the output will arrive in the same window and they may be difficult to differentiate.

Sending SIGINT from within a MATLAB GUI

From within a MATLAB GUI application, I'm starting an external program (a console application on Windows) that takes care of reading data from a measurement system. The data is stored in several files that are processed by the MATLAB application as soon as the external program has finished. The problem is this:
The external program, when run on the command line, can be gracefully stopped by issuing a SIGINT (i.e. by pressing Ctrl + C). A signal handler traps the SIGINT and shuts down the program. Is there a way to do this from within the MATLAB GUI application, by pushing an "abort" button?
After many hours of searching I stumbled upon http://www.caam.rice.edu/~wy1/links/mex_ctrl_c_trick/ which shows how to detect SIGINT in a MEX file. Letting a MEX call the external program might work (although I'm not sure about the details yet). However, it still requires Ctrl + C to stop the program. How can I send the SIGINT via push button in my GUI?
If you start your external program in Cygwin, then Cygwin will give it a PID. Using this PID you can use Cygwin's kill command to send signals to the process. So start the program from Cygwin. In MATLAB you can use !ps (where ! means call external shell command) to get a list of Cygwin PID's and then !kill -s signal pid to send a signal to the program. To make it happen from a MATLAB GUI let the callback from some button call !kill.