Skip to content

Instantly share code, notes, and snippets.

@crosstyan
Last active May 24, 2024 07:43
Show Gist options
  • Save crosstyan/87d6ff52e1dc8fc750dd193e8b51a13a to your computer and use it in GitHub Desktop.
Save crosstyan/87d6ff52e1dc8fc750dd193e8b51a13a to your computer and use it in GitHub Desktop.
a demo of closure with Matlab (R2023b)
% https://www.mathworks.com/matlabcentral/answers/439671-why-i-cannot-define-a-function-in-live-script
[inc, get] = createCounter();
inc();
inc();
disp(get());
% https://www.mathworks.com/help/matlab/function-handles.html
obj = createCounterMap();
disp(obj);
inc = obj("inc");
get = obj("get");
inc();
inc();
disp(feval(obj("get")));
functions(obj("get"))
functions(@(x) x+1)
obj = createCounterStruct()
obj.inc();
obj.inc(123);
disp(obj.get());
% https://www.mathworks.com/help/matlab/matlab_prog/fundamental-matlab-classes.html
function [inc, getter] = createCounter()
count = 0;
function increment()
count = count + 1;
end
function c = get_count()
c=count;
end
inc = @increment;
getter = @get_count;
end
% https://www.mathworks.com/help/matlab/ref/dictionary.html
function m = createCounterMap()
count = 0;
function increment()
count = count + 1;
end
function c = get_count()
c=count;
end
m = dictionary("inc", @increment, "get", @get_count);
end
% https://www.mathworks.com/help/matlab/ref/struct.html
% https://www.mathworks.com/help/matlab/ref/arguments.html
% https://www.mathworks.com/help/matlab/matlab_prog/customize-code-suggestions-and-completions.html
% https://www.mathworks.com/help/matlab/input-and-output-arguments.html
function s = createCounterStruct()
count = 0;
function increment(varargin)
% Argument blocks are not supported in nested functions,
% abstract methods, or handle class destructor methods.
% https://www.mathworks.com/help/matlab/matlab_prog/parse-function-inputs.html
p = inputParser;
% mustBeFinite
% isnumeric
addOptional(p, "val", 1, @isfinite);
parse(p, varargin{:});
count = count + p.Results.val;
end
function c = get_count()
c=count;
end
s = struct("inc", @increment, "get", @get_count);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment