onCleanup
Cleanup tasks upon function completion
Description
cleanupObj = onCleanup(
creates an object that, when destroyed, executes the function
cleanupFun
)cleanupFun
. MATLAB® implicitly clears all local variables at the termination of a
function, whether by normal completion, or a forced exit, such as an error, or
Ctrl+C.
If you reference or pass cleanupObj
outside your function, then
cleanupFun
does not run when that function terminates.
Instead, it runs whenever MATLAB destroys the object.
Examples
Input Arguments
Tips
Avoid using nested functions during cleanup. MATLAB can clear variables used in nested functions before the cleanup function tries to read from them.
If your program contains multiple cleanup objects, MATLAB does not guarantee the order that it destroys these objects. If the order of your cleanup functions matters, define one
onCleanup
object for all the tasks.If you save an
onCleanup
object, MATLAB displays a warning and does not save thecleanupFun
cleanup task.
Extended Capabilities
Version History
Introduced in R2008a