Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MATLAB have an exit event?

Tags:

matlab

Is there a way to know when an MATLAB exits? I wanted to do some work, for example, release some resource, print some logs... I could add some code at some class's destructors. But since we cannot determine the order that MATLAB calls destructors, I am not sure which one is the last one so I can release the resource.

Can we register any callback to the MATLAB exit event if there exists such an event...?

like image 978
Joe C Avatar asked Nov 29 '16 19:11

Joe C


2 Answers

There is no exit event I know of that's thrown when exiting from a function or MATLAB itself. However, there are two things you can do to handle final cleanup:

  1. Use onCleanUp objects: When exiting from a function, variables in the local workspace are destroyed (and exiting from MATLAB itself will destroy objects in the base workspace). When working with resources (files, etc.), good practice is to create an onCleanUp object to handle those resources in an exception-safe manner. This is discussed in more detail in the documentation and this question: How do you handle resources in MATLAB in an exception safe manner? (like “try … finally”)

  2. Create a finish.m file: When quitting MATLAB, it will look on the search path for a file named finish.m and run that code before terminating.

like image 142
gnovice Avatar answered Oct 19 '22 03:10

gnovice


You can place any cleanup actions in the finish.m file.

Similar to startup.m, MATLAB executes this file (when found on the MATLAB search path) just prior to program termination.

Also worth looking into is onCleanup. This simple class creates an object that, when destroyed, runs the function registered during object creation. This is extremely useful when dealing with files for example:

fid = fopen(filename, 'r');
OC = onCleanup(@() any(fopen('all')==fid) && fclose(fid));

% ...file reading and processing here
% ERROR HAPPENS HERE!
% ... more processing here

fclose(fid);

meaning, the file handle fid is still closed, even though the normal fclose(fid) was not reached. This is because the object OC was cleared implicitly by MATLAB after the error.

like image 6
Rody Oldenhuis Avatar answered Oct 19 '22 05:10

Rody Oldenhuis