compare anonymous function handles
5 views (last 30 days)
Show older comments
The following comparison of two function handles should return true in my opinion
f1=@(x,y)(x*y)
f2=@(x,y)(x*y)
isequal(f1,f2)
However, R2016a returns false on this comparison, which is a bug in my opinion. According to the documentation:
Unlike handles to named functions, function handles that represent the same anonymous function are not equal. They are considered unequal because MATLAB cannot guarantee that the frozen values of nonargument variables are the same
In my example, both x and y ARE argument variables. The result is always the same for given arguments. What do you think?
0 Comments
Answers (2)
Matt J
on 18 Apr 2016
Edited: Matt J
on 18 Apr 2016
The documentation that you quoted is referring to situations like this:
>> a=1; f1=@(x,y)(x*y+a);
>> a=2; f2=@(x,y)(x*y+a);
These display the same,
>> f1,f2
f1 =
@(x,y)(x*y+a)
f2 =
@(x,y)(x*y+a)
but give different output for the same input arguments:
>> f1(0,0), f2(0,0)
ans =
1
ans =
2
If you consider 2 anonymous functions to be equal if they display the same, you could compare them this way,
>> strcmp(func2str(f1),func2str(f2))
ans =
1
Walter Roberson
on 18 Apr 2016
funinfo(1) = functions(f1);
funinfo(2) = functions(f2);
strcmp(funinfo(1).function, funinfo(2).function) && isequal(funinfo(1).workspace{1}, funinfo(2).workspace{1})
3 Comments
Walter Roberson
on 22 Apr 2016
I doubt Mathworks will change this behaviour any time soon. The alternative would require that Mathworks search all existing function handles, in all scopes, to see if it could find a match.
I suggest you grab a File Exchange Contribution such as http://www.mathworks.com/matlabcentral/fileexchange/34565-micro-cache--memoize-cache-function-results and create a routine that takes in strings and return function handles -- we know that you can convert to string since you do not use any variables from your workspace. The routine would keep a copy of each function handle it generates and upon being presented with the same string would return the same function handle, which would then permit isequal() to operate.
See Also
Categories
Find more on Variables in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!