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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Software Development Life Cycle (SDLC)
Software development life cycle (SDLC) is a structured process that is used to design, develop, and test good-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Waterfall Model - Software Engineering
The Waterfall Model is a Traditional Software Development Methodology. It was first introduced by Winston W. Royce in 1970. It is a linear and sequential approach to software development that consists of several phases. This classical waterfall model is simple and idealistic. It is important because
13 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read