How to make a function handle from variable consisting of a function

2 views (last 30 days)
I have a problem like this for example.
x = sym('x',[7,1]);
phi = [ (10001*x2)/800000 - (10001*x1)/400000 + (10001*x3)/600000 - (10001*x4)/1600000 + (10001*x5)/3000000 + (10001*x6*x7)/200000];
% ** This phi was copied from output just so you see how it looks
Is there a way I can make a function handle kind of like this?
phi1 = @(x)phi
(I know this doesn't work but hopefully you get what I am trying to do) Basically I can't explicitly write out the function because it is generated from another algorithm. I don't know the syntax, or if you can even do this.
Also, can someone explain the difference between the operator @ and matlabFunction? Thanks!

Accepted Answer

Star Strider
Star Strider on 13 Jan 2016
You can’t get there directly because of the way the Symbolic Math Toolbox creates function calls with matlabFunction:
phi0 = matlabFunction(phi);
phi1 = @(x) phi0(x(1),x(2),x(3),x(4),x(5),x(6),x(7))
A subs call didn’t work, so typing it manually was the only option.
  4 Comments
Kristoffer Lindvall
Kristoffer Lindvall on 13 Jan 2016
I am analytically iterating forth a set of equations that I solve with a semi implicit root solver. The entire program, which is too long to show here, is using a spectral method to solve a time dependent problem by taking as big of a time interval "leap" as possible for it to converge. I am trying to make my code run as fast in Matlab as it does in Maple. Matlab should include a way to make function handles on the fly like we just did without using the matlabFunction command.
I realize it is hard for me to explain why I need to do it analytically. That is how the algorithms for the method are written. I am struggling to find a way to do it numerically.
Star Strider
Star Strider on 13 Jan 2016
My approach would be to use the Optimization Toolbox function fsolve to find the roots, assuming I understood the problem well enough to formulate the function to give to it, and if it is possible to do it without the Symbolic Math Toolbox.
The Symbolic Math Toolbox solve function would avoid the necessity of creating an anonymous function, but I doubt it would be faster.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!