Problem 44345. MATLAB Counter
Solution Stats
Problem Comments
-
9 Comments
My function works directly as described - but does not manage to pass the test suite ... what is wrong?
%%
function varargout = counter(varargin)
persistent add base
if isempty(varargin)
base = base + add;
varargout{1} = base;
end
if numel(varargin) > 1
add = varargin{2};
base = varargin{1}-add;
end
end
For anyone needing a gentle refresher (like I did) on nested anonymous functions:
https://www.mathworks.com/matlabcentral/cody/problems/24-function-iterator
Cody's Problem 24 might be of relevance, but note that so far very few of the correct solutions to the present problem (Problem 44345) have used anonymous functions, whereas all of the correct solutions have used named functions (some nested, some not).
Correction: there is a solution here (Solution 1308690) which only uses an anonymous function, without calling a named user function.
Either (or both) of the following pages may be of interest in tackling this problem: https://mathworks.com/help/matlab/matlab_prog/nested-functions.html and https://mathworks.com/help/matlab/matlab_prog/share-data-between-workspaces.html .
It's the best problem in Cody:Easy
You can also use class definition to solve it, amazing!
the tests can be strengthened a bit, to allow multiple counters
g = counter(1,2);
h = counter(3,5);
assert(isequal([1 3 5 3 8 13], [g() g() g() h() h() h()]));
:
One way to solve this problem:
https://paste.ubuntu.com/p/nCFk9p7XNM/
Solution Comments
-
1 Comment
persistent and function handle?
-
1 Comment
Due to the use of persistent variables and the conditional statements used, this solution would fail if the test suite were modified to include two tests in a row with the same increment value.
-
1 Comment
?
-
1 Comment
I just learned how to use the combined fx handle and nested fx!
Problem Recent Solvers249
Suggested Problems
-
1772 Solvers
-
Remove the small words from a list of words.
1153 Solvers
-
578 Solvers
-
Numbers with prime factors 2, 3 and 5.
413 Solvers
-
Reverse the elements of an array
822 Solvers
More from this Author29
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!