Accessing variables on onCleanUp function
Mostrar comentarios más antiguos
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!
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Creating, Deleting, and Querying Graphics Objects en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!