This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Cleanup tasks upon function completion


cleanupObj = onCleanup(cleanupFun)



cleanupObj = onCleanup(cleanupFun) creates an object that, when destroyed, executes the function 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.


collapse all

Save the following code in action.m and type action in the Command Window.

function [] = action()
f = figure;
finishup = onCleanup(@() myCleanupFun(f));
disp('Display Figure')

function myCleanupFun(f)
disp('Close Figure')
Display Figure
Close Figure

Pass your own script to the onCleanup object so that it executes when MATLAB destroys the cleanup object.

Save the following code in cleanup.m.

disp('You are now in the temporary folder')

Save the following code in youraction.m and type youraction in the Command Window.

function [] = youraction
	changeup = onCleanup(@cleanup);
	disp('Execute Code')
Execute Code
You are now in the temporary folder

Input Arguments

collapse all

Clean-up task, specified as a handle to a function.

You can declare any number of onCleanup objects in a program file. However, if the clean-up tasks depend on the order of execution, then you should define only one object that calls a script or function, containing the relevant clean-up commands.

You should use an anonymous function handle to call your clean-up task. This allows you to pass arguments to your clean-up function.

Example: @() fclose('file.m')

Example: @() user_script

Example: @() function(input)

Data Types: function_handle


  • Avoid using nested functions during cleanup. MATLAB can clear variables used in nested functions before the clean-up 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 the cleanupFun clean-up task.

Introduced in R2008a