%# this code is adapted from %# https://research.wmz.ninja/articles/2017/05/closures-in-matlab.html function ctr = test_nested_func(n) if nargin < 1 n = 2; end %# those values are set at first invocation n0 = n; %# %# persistent A regmat x y; %# A = randn (n); ampl = 1e-3; x = linspace(-1, 1, n); x = x(:); y = 2 + 3*x + ampl*A(:, 1); regmat = ones (length (x), 2); regmat(:, 2) = x; if exist('x') disp(size(x)); disp(lscov(regmat, y) - [2; 3]); end function increase() n = n + 1; disp(sprintf('Original: %d actual: %d', n0, n)); ampl = ampl * 2; who %# expected: A ampl ctr n regmat x y if exist('x') disp(size(x)); disp(lscov(regmat, 2+3*x+ampl*A(:, 1)) - [2; 3]); end end function decrease() n = n - 1; disp(sprintf('Original: %d actual: %d', n0, n)); ampl = ampl / 2; if exist('x') disp(size(x)) disp(lscov(regmat, 2+3*x+ampl*A(:, 1)) - [2; 3]); end end function reset() n = 0; ampl = 1e-3; end function set_count(m) n = m; end function resu = get_count() resu = n; end ctr.n0 = n; ctr.increase = @increase; ctr.decrease = @decrease; ctr.reset = @reset; ctr.set_count = @set_count; ctr.get_count = @get_count; who end