How can I replace symbolic variables to solve a nonlinear system using fsolve
Ältere Kommentare anzeigen
I am working on a system of nonlinear equations, for example:
3*u1^2 + 2*u2 - 5 = 0;
4*u1 - 3*u2^3 + 10 = 0;
where u1 and u2 are symbolic variables. I'm having much difficulties replacing u1 and u2 with x(1) and x(2) in @fun, suitable for fsolve:
x = fsolve(fun,x0,options)
The problem is that the system of equations (and number of variables) is too large to do this manually ... Is anyone aware of an elegant/automatic solution?
Akzeptierte Antwort
Weitere Antworten (3)
Walter Roberson
am 11 Aug. 2012
Consider using matlabFunction() to transform the symbolic expression into a function handle that can be passed to fsolve().
To handle the assignment of the vector x into other variable names, use a small routine,
function result = split_and_call( fh, x )
xcell = num2cell(x);
result = fh( xcell{:} );
end
1 Kommentar
annona
am 12 Sep. 2012
If I can ask about your answer,How to call this function?
'fh' is the output of the 'matlabFunction' and 'x' is what ?? Is it the initial guess for 'fsolve'?
Star Strider
am 11 Aug. 2012
Starting with:
Eqn1 = 3*u1^2 + 2*u2 - 5 == 0
Eqn2 = 4*u1 - 3*u2^3 + 10 == 0
If you simply want the numeric solutions, this works:
[u1, u2] = solve(Eqn1, Eqn2)
Continuing on, replacing u1 and u2 with x(1) and x(2) is fairly straightforward:
Eqn1 = subs(Eqn1, {'u1','u2'}, {'x(1)','x(2)'})
yields:
Eqn1 =
2*x(2) + 3*x(1)^2 - 5 == 0
and
Eqn2 = subs(Eqn2, {'u1','u2'}, {'x(1)','x(2)'})
yields:
Eqn2 =
4*x(1) - 3*x(2)^3 + 10 == 0
For some reason I can't figure out, I can't make these work:
Eqn1m = matlabFunction(3*u1^2 + 2*u2 - 5)
Eqn2m = matlabFunction(4*u1 - 3*u2^3 + 10)
even though matlabFunction works with other equations and variables, and these work without problems:
Eqn1m = matlabFunction(3*x1^2 + 2*x2 - 5)
Eqn1m =
@(x1,x2)x2.*2.0+x1.^2.*3.0-5.0
and
Eqn2m = matlabFunction(4*x1 - 3*x2^3 + 10)
Eqn2m =
@(x1,x2)x1.*4.0-x2.^3.*3.0+1.0e1
However matlabFunction won't preserve the substitutions for x(1) and x(2), so you need to vectorize and then create your own anonynous functions:
Eqn1v = vectorize(Eqn1)
Eqn1v =
2.*x(2) + 3.*x(1).^2 - 5 == 0
Eqn2v = vectorize(Eqn2)
Eqn2v =
4.*x(1) - 3.*x(2).^3 + 10 == 0
however you're going to have to change them a bit if you want to use them with fsolve.
NOTE: I have no idea why matlabFunction doesn't like u1 and u2 as variables. I obviously declared them in my syms statement and they work everywhere else in the code, just not in matlabFunction. Weird.
Kategorien
Mehr zu Symbolic Math Toolbox finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!