onCleanup
Cleanup tasks upon function completion
📝Syntax
onCleanup(function_handle)
obj = onCleanup(function_handle)
📥Input Arguments
Parameter Description
function_handle a function handle to execute upon cleanup.
📤Output Arguments
Parameter Description
obj an onCleanup object that executes the specified function handle upon cleanup.
📄Description

onCleanup creates an object that executes a specified function handle when the object is cleared or goes out of scope, allowing for cleanup tasks to be performed automatically upon function completion.

cancel(obj) or obj.cancel() prevents the cleanup function from being executed.

💡Examples
a = onCleanup(@() disp('Cleanup executed'))
clear a
function cleanupExample(doCancel)
  disp('Display Figure')
  f = figure;
  cleanup = onCleanup(@()atTheEnd(f));
  if doCancel
    cleanup.cancel(); % other syntax: cancel(cleanup);
  end
  sleep(5)
end

function atTheEnd(f)
disp('Close Figure')
close(f)
end

cleanupExample(false);
cleanupExample(true);
🕔Version History
Version Description
1.16.0 initial version
Edit this page on GitHub