No BSD License  

Highlights from
Closures in the MATLAB Language

from Closures in the MATLAB Language by Jim Hunziker
Demonstration of Closures in the MATLAB Language

makeIncrementer(n)
function f = makeIncrementer(n)
% makeIncrementer(n) returns a function that returns n.
%
% Each successive time the returned function is called, it returns a
% number that is one greater than the last time it was called.  No
% global workspace variables are used.


function val = g()
% g() captures n from its enclosing scope and keeps a private
% copy.  Each time g() is called, the current value of n is
% returned.
val = n;
n = n + 1;
end

% Return a function handle to g().
f = @g;

end

Contact us at files@mathworks.com