Clean Up When Functions Complete in MATLAB
Last Updated :
24 Apr, 2025
While working in MATLAB, handling the workspaces is crucial for the proper working of multiple scripts and functions. That is why it is a healthy habit to clean up the MATLAB workspace once a function execution is completed.
Some of the requirements for performing a cleanup routine, cleaning up all the files, scripts, and/or functions of the last work environment, could be:
- Removing all the variables from workspace that are not required.
- Freeing up any used memory.
- Removing locks placed upon any file in the MATLAB session.
- Restoration of the MATLAB path, if it was tempered with.
- Close any files (scripts or functions) that were opened for access.
In this article, we shall use the onCleanup function of MATLAB to perform different sorts of cleanup tasks in MATLAB.
Syntax
The cleanup function takes a function handle as its input argument, which is performed when MATLAB picks up a cleanup object.
cleanUpObj = onCleanup(function_handle)
The input function handle could be an anonymous function, which generally is the case and executes the input handle once the function containing the onCleanup object is read into the memory.
Now we shall see some uses of the onCleanup function with example.
Closing up opened files
In this example, we shall see how to close an opened file once the function accessing it, is completely executed.
Matlab
function geeks
file = fopen("data.txt","r");
%creating the cleanup object which
%will close the opened file safely
%once the main function is executed
cleanob = onCleanup(@()fclose(file));
end
In the above function, we create a file object which holds the 'data.txt' file in read only mode. Then, we create a cleanup object which calls the oncleanUp function with the anonymous function handle that closes the opened file once the geeks function's execution is completed.
The point to be noted here is that it does not matter where the onCleanup object is initialized in the function; MATLAB will always execute in the end of function execution, which makes the onCleanup function highly useful, in case the user needs to run some tasks in the end of the function execution(which we shall see in the next example).
Output:
As it can be seen, the function executes without any error, which confirms that the file has been closed safely.
Scheduling Task at the End of Function Execution
As explained earlier as well, the onCleanup object is always executed upon the function completion, irrespective of its declaration. This property can be used to schedule certain tasks at the end of function execution but, the same task can be constructed as the onCleanup object at anytime in the function definition. See the following example.
Matlab
function geeks
%displaying the start of function
disp('Main function opened')
%creating the cleanup object
cleanob = onCleanup(@()cleanup);
disp('Function Running...')
end
%function to alert the end
%of geeks function execution
function cleanup
disp('Main function Closed and Clean Up done!')
end
Now, if the cleanob was any ordinary object, it would have been executed in the top to bottom approach of execution however, this is not the case as cleanob is a cleanup object thus, it will execute on the end of the geeks function execution.
Output:
Here, we can see that the line 4 executed before the line 3, which should have been the case if cleanob was an ordinary object. Once MATLAB detects that cleanob is a cleanup object, it moves to the following statements, run all the statements in the function definition and then, executes the function handle passed in the onCleanup function i.e, the cleanup function in above example.
Conclusion
This article discussed the onCleanup function of MATLAB which is used to perform tasks at the end of a function execution in MATLAB. We discussed some scenarios where the cleanup object could be used such as scheduling some tasks at the end of a function execution.
For further understanding, user could refer to the MATLAB documentation.
Similar Reads
How to create a function in MATLAB ?
A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functions which are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions. Syntax: fun
2 min read
User defined function in MATLAB
Functions let you do a specific task. User defined functions are the functions created by the users according to their needs. This article explains how the user defined function in MATLAB is created. Syntax : function [a1,...,an] = func(x1,...,xm) func is the function name a1,...,an are outputs x1,.
2 min read
Anonymous Functions in MATLAB
A block of code that is organized in such a way that is reusable for the entire program. Functions are used for reducing efforts made by writing code and making the program short, and easily understandable. There are different syntaxes for declaring a function in different programming languages. In
5 min read
Creating Function in Files in MATLAB
MATLAB is a high-performance language that is used for matrix manipulation, performing technical computations, graph plottings, etc. It stands for Matrix Laboratory. Functions:The function is a set of statements or commands, which take input/s as parameters and return output. We write functions to
2 min read
Configure the Run Button for Functions in MATLAB
Functions are parts of program files that process inputs and generate outputs. Set the Run button to execute any additional Editor setup or functions that need argument values to be entered. To configure the Editor's Run button, click Run and type one or more run commands. We'll examine a setup exam
2 min read
Scripts and Functions in MATLAB
In MATLAB there are a different kinds of files dedicated to MATLAB codes. They are the following: ScriptLive ScriptFunction only fileClass fileNow only the live script is the only one of these which has a different extension name; all other three use the standard .m extension. In this article, we sh
2 min read
Filter Function in MATLAB
The filter function or 1-D digital filter is a function in MATLAB that is used to filter a given noisy data by removing the noise in the data and sharpening or smoothing the input function. As MATLAB provides a dedicated Signal Processing Toolset, the filter function comes handy to remove noise from
3 min read
Calling a Python function from MATLAB
We can call the Python functions and objects directly from MATLAB. To call Python functions from MATLAB, need to install a supported version of  Python. MATLAB supports versions 2.7, 3.6, and 3.7 MATLAB  loads Python when you type py.command. py.modulename.functionname Below examples shows how to ca
2 min read
Private Functions in MATLAB
Private functions are useful when you want to limit the scope of a function. Here we will learn how to create private functions and also use them. Private functions are primary functions that are visible only to a limited group of other functions. Generally, we make private functions, if we want to
2 min read
function command in Linux with examples
The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient. The function can be created in the u
2 min read