How do I convert multivariate function handle to symbolic function? Anyone has any ideas?

My function handle is as follows,
g=@(p)p(1)+p(2)
I can compute using function handle using something like
g([1,2])
Now I want to convert it to a symbolic function, but seems MATLAB has trouble assuming p(1) and p(2) as symbol. So
syms p(1)
sym(g)
doesn't work. I guess I might need to change p(1),p(2) to p1,p2, but this is hard, too. Anyone can help?

Answers (1)

P = sym('p', [1 2]);
G = g(P);
now G will be a symbolic expression in p1, p2. You can then convert it to a symbolic function by using
Gsym = feval(symengine, 'fp::unapply', G, P(1), P(2));

4 Comments

Thanks, could you please explain the second line a bit? Also, how do I call Gsym? It seems Gsym(1,2) doesn't work and can't compute Gsym at (1,2)
G = g(P) is just calling the function handle g passing in the vector [p1 p2] so the result for that g would be the symbolic expression p1+p2 .
I have no information about the ability to use sym() to convert an anonymous function to a symbolic function. I would not have guessed that it could be done, but I do not know.
Accordingly, the third line is the code to convert the expression G into a symbolic function by using the facilities of the symbolic engine, http://www.mathworks.com/help/symbolic/mupad_ref/fp-unapply.html . The result will be a symbolic function. Using it might require, for example,
feval(symengine, Gsym, 1, 2)
A symbolic function is a MuPAD procedure that returns one or more outputs and which might have 0 or more inputs and 0 or more statements.
You can also have anonymous functions in MATLAB which happen to involve terms that are symbolic. I suspect that this must be pretty close to how
syms f(x)
is implemented, except with the default variables decided by the name of the dummy arguments of the anonymous function. I do not, however, have the Symbolic Toolbox to check this detail.

Sign in to comment.

Tags

No tags entered yet.

Asked:

on 1 Feb 2016

Commented:

on 2 Feb 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!