onCleanup — Run a function automatically when a cleanup object is deleted or cleared.
onCleanup(f) creates a handle object that invokes the zero-input function handle f when the object is deleted or cleared from the workspace. It is useful for restoring state, closing files, removing temporary folders, and other cleanup tasks.
Syntax
cleanupObj = onCleanup(cleanupFun)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
cleanupFun | Any | Yes | — | Zero-input function handle to invoke during cleanup. |
Returns
| Name | Type | Description |
|---|---|---|
cleanupObj | Any | Handle object that invokes the cleanup function when deleted or cleared. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:onCleanup:InvalidCallback | The cleanup function is not a function handle or closure. | onCleanup: cleanupFun must be a function handle |
RunMat:onCleanup:InvalidObject | A cleanup operation targets a value that is not an onCleanup object. | onCleanup: invalid cleanup object |
RunMat:onCleanup:GcFailure | The cleanup object target cannot be allocated, rooted, or mutated. | onCleanup: internal object storage failed |
How onCleanup works
cleanupObj = onCleanup(cleanupFun)requirescleanupFunto be a function handle or anonymous-function closure.- The cleanup function is invoked with zero input arguments and zero requested outputs.
- The callback runs at most once for each cleanup object.
delete(cleanupObj)invokes the callback immediately through the onCleanup handle method.cancel(cleanupObj)deactivates the cleanup object without invoking the callback.clear cleanupObj,clear, andclearvarsrun active cleanup callbacks before removing the corresponding workspace values.
Does RunMat run onCleanup on the GPU?
onCleanup creates and manages a host lifecycle object. It does not participate in fusion and does not create GPU-resident outputs.
Examples
Restore state when a workspace variable is cleared
old = pwd;
cleanupObj = onCleanup(@() cd(old));
cd(tempdir);
clear cleanupObjExpected output:
% The current folder is restored before cleanupObj is removed.Close a file even when later code fails
fid = fopen('data.txt', 'w');
cleanupObj = onCleanup(@() fclose(fid));
fprintf(fid, 'sample\n');
% cleanupObj closes fid when it is deleted or cleared.Cancel cleanup when ownership has been transferred
cleanupObj = onCleanup(@() disp('cleanup'));
cancel(cleanupObj);
delete(cleanupObj)Expected output:
% No cleanup message is printed because cancel disabled the callback.Using onCleanup with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how onCleanup changes the result.
Run a small onCleanup example, explain the result, then change one input and compare the output.
FAQ
Can I pass arguments directly to the cleanup function?⌄
No. Use an anonymous function that captures the values you need, for example onCleanup(@() fclose(fid)).
Does the callback run more than once if I call delete multiple times?⌄
No. The object is deactivated before the callback is invoked, so later delete, clear, or clearvars paths are no-ops.
Does cancel delete the object?⌄
cancel only deactivates the callback. The handle value can still exist, but it will no longer run the cleanup function.
Does GPU residency matter?⌄
No. The cleanup handle is a host object. Any GPU work is determined by the callback body itself.
Related Introspection functions
addprop · class · clear · clearAllMemoizedCaches · clearCache · clearvars · dbclear · dbstack · dbstatus · dbtype · evalc · findprop · getcallinfo · inputParser · isa · ischar · isdeployed · iskeyword · ismethod · isobject · isstring · isUnderlyingType · keyboard · matlab.metadata.DynamicProperty.delete · memoize · metaclass · mislocked · mlock · munlock · namelengthmax · stats · superclasses · underlyingType · verLessThan · version · which · who · whos
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how onCleanup is executed, line by line, in Rust.
- View the source for onCleanup in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.