Hello!
I have a problem! This is my first question here, so sorry if it's already answered :)
I have a non linear function
f=@(x,y)[x^3+10*x-y-5; x+y^3-10*y+1]
and I need it use in fsolve, but it won't work if the function isn't writen as
f=[x(1)^3+10*x(1)-x(2)-5; x(1)+x(2)^3-10*x(2)+1]
Can it be somehow rewriten it to the correct form? Is there any way? I can't just rewrite the function because then the rest of the code won't work and subs won't work with x(1) and x(2).
Thank you!

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 18 Dez. 2020

0 Stimmen

initial_conditions = randn(1,2)
initial_conditions = 1×2
-0.1679 1.7828
f=@(x,y)[x^3+10*x-y-5; x+y^3-10*y+1]
f = function_handle with value:
@(x,y)[x^3+10*x-y-5;x+y^3-10*y+1]
objective = @(XY) f(XY(1), XY(2))
objective = function_handle with value:
@(XY)f(XY(1),XY(2))
fsolve(objective, initial_conditions)
Equation solved. fsolve completed because the vector of function values is near zero as measured by the value of the function tolerance, and the problem appears regular as measured by the gradient.
ans = 1×2
0.5024 0.1506
and subs won't work with x(1) and x(2)
That implies you have access to the Symbolic Toolbox. If so then
syms x y
objective = matlabFunction(f(x,y), 'vars', {[x, y]})
objective = function_handle with value:
@(in1)[in1(:,1).*1.0e+1-in1(:,2)+in1(:,1).^3-5.0;in1(:,1)-in1(:,2).*1.0e+1+in1(:,2).^3+1.0]
and that will produce an anonymous function that expects vector input.
... Or you could
syms x y
sol = solve( f(x,y) );
mask = isAlways(imag(sol.x) == 0) & isAlways(imag(sol.y) == 0);
xsol = sol.x(mask)
xsol = 
root(σ1,z,1)3+10root(σ1,z,1)1root(σ1,z,4)3+10root(σ1,z,4)1root(σ1,z,7)3+10root(σ1,z,7)1where  σ1=z930z7+3z6+300z560z4987z3+300z2129z+16
ysol = sol.y(mask)
ysol = 
root(σ1,z,1)root(σ1,z,4)root(σ1,z,7)where  σ1=z930z7+3z6+300z560z4987z3+300z2129z+16
double([xsol,ysol])
ans = 3×2
0.5024 0.1506 0.7627 3.0702 0.1775 -3.2196
This shows you that there are three real solutions. Which one you will get with fsolve() will depend upon your starting conditions.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by