How can I save variables using onCleanup in Matlab?
I have a Matlab script that is running on a cluster. If the time exceeds some time, it is killed. I want to use onCleanup to save some (or all) of the variables before the script is killed.
I've tried the following:
function [] = test
ita = 5;
finishup = onCleanup(@() save('test.mat','ita'));
pause(7200);
disp('done')
exit
end
I think the variable "ita" is killed before onCleanup is executed, it does not find this variable. The same appears if I turn the function into a script.
ita = 5;
finishup = onCleanup(@() save('test.mat','ita'));
pause(7200);
disp('done')
exit
How can I make it right?
Of course, if I use onCleanup inside a function, then it is executed as soon as the function stops (e.g. ctrl + c). If I use a script, then onCleanup is only executed when Matlab exits.
source to share
I would definitely not recommend this ... but this is the solution to your problem. Set ita
as global
, then use a subfunction call to save the cleanup / MAT file. This method ita
is in scope.
This worked when either the function finished or I pressed Ctrl + C while paused.
function [] = test()
global ita
ita = 5;
finishup = onCleanup(@() cleanMe());
pause(7200);
disp('done')
function cleanMe()
global ita
save('test.mat','ita')
source to share