Closures in the MATLAB Language

Version 1.0.0.0 (729 Bytes) by Jim Hunziker
Demonstration of Closures in the MATLAB Language
1.5K Downloads
Updated 4 Jan 2008

No License

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 (2024). Closures in the MATLAB Language (https://www.mathworks.com/matlabcentral/fileexchange/18223-closures-in-the-matlab-language), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R14SP2
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Counter and Timer Input and Output in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.0.0.0