Problem 1 is you're passing some arguments to example, yet your function doesn't take any argument. One would presume you'd want to do something with these arguments inside your function.
In any case, you need to think a bit more about what it is you want to do. I understand that you want your example function to keep track of the count independently if you call it with A as an argument or B as an argument.
The problem is that you don't actually call your example with A as an argument, or B as an argument, but with A(1) or B(1) or A(x) or X(y). Therefore, when the function call actually takes place, there is no more notion of A, B, X, it's just a number. You could of course keep track of different counts for different input numbers in your example function, but I don't think that's what you want?
If you wanted to keep a different count for different input numbers:
function count = countbynumber(number)
persistent m;
if isempty(m)
m = containers.Map('KeyType', 'double', 'ValueType', 'double');
end
if m.isKey(number)
count = m(number);
m(number) = m(number)+1;
else
count = 0;
m(number) = 1;
end
end
If you want to keep a different count for different name of input variable, you would have to call the function with:
c1 = countbyinputname(A);
c2 = countbyinputname(B);
c1 = countbyinputname(A);
c2 = countbyinputname(B);
That is you can't index the inputs. In which case the function itself is:
function count = countbynumber(v)
persistent m;
if isempty(m)
m = containers.Map('KeyType', 'char', 'ValueType', 'double');
end
varname = inputname(1);
if m.isKey(varname)
count = m(varname);
m(varname) = m(varname)+1;
else
count = 0;
m(varname) = 1;
end
end
I'm not sure what would happen if you were to call the function with temporaries such as A(1).
But ultimately, the best solution may be to use a handle class for which you use different instances for different variables:
classdef counter < handle
properties (SetAccess = private)
count = 0;
end
methods
function count = increment(this, x)
count = this.count;
this.count = this.count+1;
end
end
end
You'd use it like this:
counterA = counter;
counterB = counter;
c1 = counterA(A(1));
c2 = counterB(B(1));
c1 = counterA(A(2));
c2 = counterB(B(2));