MATLAB: Accessing variables on onCleanUp function

cleanup-objectglobal variablesMATLABmatlab functionvariables

Hello everyone,
I Have a function that uses several communication interfaces and instruments control.
Upon finishing the function (completion or cancelation, including CTRL+C), the function should exit and clean up the connections, as well as files that were created.
I used the cleanup object to do this, but ofcourse, unfortunately, it does not recognize local variables since MATLAB already cleaned them.
Example code:
function foo()
cleanupObj = onCleanup(@() cleanMeUp;
%instruments declaration
intrument1 = visa(...)
%folder creation
folder_path = "C:\..."
mkdir(folder_path)
some_code...
function cleanMeUp
if (exist('instrument1','var')
fclose(instrument1)
end
if (exist('folder_path','var'))
rmdir(folder_path, 's')
end
end
end
The problem is that the cleanMeUp function does not recognize instrument1 and folder_path variables as they are local.
I've tried two possible solutions, both aren't good practice and may lead to some errors.
  • Use global variables for the required variables, i.e.
function foo()
global intrument1
global folder_path
cleanupObj = onCleanup(@() cleanMeUp;
...
function cleanMeUp
global intrument1
global folder_path
if (exist('instrument1','var')
fclose(instrument1)
end
if (exist('folder_path','var'))
rmdir(folder_path, 's')
end
end
end
but I've heared this is not a good practice to use global variables, but this solution works.
  • Pass the variables to the cleanMeUp function, i.e.
function foo()
cleanupObj = onCleanup(@() cleanMeUp(intrument1,folder_path));
...
function cleanMeUp(intrument1,folder_path)
if (exist('instrument1','var')
fclose(instrument1)
end
if (exist('folder_path','var'))
rmdir(folder_path, 's')
end
end
end
The problem is that the cleanMeUp function only knows the variables according to the time cleanupObj was created, and if they are changed, it will not work properly.
Any ideas how to do this in an ideal way?
Thanks in advance!

Best Answer

function foo()
%instruments declaration
intrument1 = visa(...)
instrumentcloser = onCleanup(@()fclose(instrument1));
%folder creation
folder_path = "C:\..."
mkdir(folder_path)
folderremover = onCleanup(@()rmdir(folder_path, 's'));
end
The cleanup object should only clean up what it knows. If they change (not sure why they would), recreate the cleanup object. Note that I created the instrument and folder before the cleanup object so there's no exist test, and each cleanup object only has one task. Now if your mkdir command fails to run, the instrument will still be closed.