Write a function f = counter(x0,b) to construct a counter handle f that counts with an initial value x0 and a step size b.
E.g.,
>> f = counter(0,1) % Initialize a counter f() with initial_count = 0 and step_size = 1 >> f() ans = 0 >> f() ans = 1 >> f() ans = 2
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!
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.
f = counter(x,b);
Does using f() rerun the function counter?
?
I just learned how to use the combined fx handle and nested fx!
Find the two most distant points
1809 Solvers
Replace NaNs with the number that appears to its left in the row.
2221 Solvers
2658 Solvers
Find the maximum number of decimal places in a set of numbers
306 Solvers
398 Solvers