Let me try ....
Each time the function called counter() creates a unique function handle. This function descriptor is a function descriptor called increment, which takes its variable value and increments it by one.
So if it is called twice, as in the code (f1, f2), each time the same function (increment) is returned, but different descriptors. You have the TWICE function installed. And each of them now works independently. Since this specific function (increment) is used in the stored internal value to calculate it, you can observe how, if you call, as in your code example, the outputs [1 2 1 3 2].
A good way to better identify differences is to redefine the function as:
function fcnHandle = counter(val) value = val; function currentValue = increment value = value+1; currentValue = value; end fcnHandle = @increment; end
and calling it the following:
>> f1 = counter(0); >> f2 = counter(1000); >> output = [f1() f1() f2() f1() f2()] %
Now you will see that the output is [1 2 1001 3 1002]
Now makes more sense?
This code is created, so it uses this function descriptor attribute (it is the same, but it is copied twice).
source share