>
> Use FINDSYM to find the symbolic variables in your
> expression, then write an
> anonymous function that calls SUBS on your symbolic
> expression. Note that
> you will need to know in which order FINDSYM returns
> the variables (or if
> you know which variables are included in your
> expression, list them in the
> order you want rather than using FINDSYM):
>
> syms x y a b real
> v = [x y];
> w = [a b];
> f = w * v'
> g = @(vec) subs(f, findsym(f), vec)
>
> As I mentioned above, since findsym(f) returns 'a, b,
> x, y' that's the order
> in which values will be substituted into your
> expression.
>
> 
> Steve Lord
> slord@mathworks.com
>
>
The findsym() method works, but when I call an optimization routine it is about 10 times as slow as copying and pasting the symbolic expression into an anonymous function.
Fast code with copypaste:
g = @(a,b,x,y) a*x+b*y ; % copypaste here
loss = @(p) g(p(1),p(2),p(3),p(4));
optimization(loss);
Slower code without copypaste:
loss = @(vec) subs(f, findsym(f), vec)
optimization(loss);
Both 'loss' functions give the same values at trial values of a,b,x,y (when the parameters are in the same order), and both require 16 bytes as class 'function_handle array'.
Where does the speed discrepancy come from?
