You are now following this Submission
- You will see updates in your followed content feed
- You may receive emails, depending on your communication preferences
Sometimes in MATLAB, a programmer might want to write functions that maintain state without exposing that state to the global workspace.
A closure is a concept in computer science that describes the execution of a function that has privately captured variables from an enclosing scope. Through nested functions and function handles, a user can create closures in MATLAB.
By privately capturing variables, a closure can help the programmer avoid maintaining global state variables and write more modular code.
This simple example shows how to write a function that takes an argument n and returns another function. This returned function can be called multiple times, returning n plus the number of times the function has been called previously.
Here is another useful application of closures. Suppose you have to do an operation that needs to work on every item in a sequence. There are many many items, and you can't afford the space to calculate them all at once, store them, and do the operation on them in a loop.
But you have plenty of time and CPU power. You can make a function like makeIncrementer (in the attached example) that remembers where it was in the sequence and generate each item on demand.
Learning to use closures can make your MATLAB routines smaller and your code more modular.
Cite As
Jim Hunziker (2026). Closures in the MATLAB Language (https://www.mathworks.com/matlabcentral/fileexchange/18223-closures-in-the-matlab-language), MATLAB Central File Exchange. Retrieved .
General Information
- Version 1.0.0.0 (729 Bytes)
-
No License
MATLAB Release Compatibility
- Compatible with any release
Platform Compatibility
- Windows
- macOS
- Linux
| Version | Published | Release Notes | Action |
|---|---|---|---|
| 1.0.0.0 |
