Closures in the MATLAB Language

버전 1.0.0.0 (729 Bytes) 작성자: Jim Hunziker
Demonstration of Closures in the MATLAB Language
다운로드 수: 1.5K
업데이트 날짜: 2008/1/4

라이선스 없음

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.

인용 양식

Jim Hunziker (2025). Closures in the MATLAB Language (https://kr.mathworks.com/matlabcentral/fileexchange/18223-closures-in-the-matlab-language), MATLAB Central File Exchange. 검색 날짜: .

MATLAB 릴리스 호환 정보
개발 환경: R14SP2
모든 릴리스와 호환
플랫폼 호환성
Windows macOS Linux
카테고리
Help CenterMATLAB Answers에서 Counter and Timer Input and Output에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!
버전 게시됨 릴리스 정보
1.0.0.0