fsolve with variable number of unknowns
Show older comments
I have a set of nonlinear equations I would like to solve using fsolve. First I define a function F and then I solve it in Matlab.
function F = myfun (x)
a*x(2)^2+b*x(1)+c=0
c*x(2)^2+d*x(1)+c=0
e*x(2)+f*x(1)+c=0
in which a,b,c,d,e,f are constants.
My questions are the following:
1) Is it possible to define a Matrix A with the constants and multiply by the vector of unknowns (x(2),x(1))?
1) If I want to add more unknowns to the nonlinear system of equations do I need to rewrite the function and add it manually? Is there a more elegant way?
Regards
Answers (2)
Matt J
on 7 Apr 2015
A1=[a b c; c d c];
A2=[e f c];
x=fsolve(@(x)myfun(x,A1,A2),x0);
function F = myfun (x, A1, A2)
p1=[x(2)^2, x(1), 1].';
p2=[x(2), x(1),1].';
F=[A1*p1;A2*p2]
end
1 Comment
If I want to add more unknowns to the nonlinear system of equations do I need to rewrite the function and add it manually? Is there a more elegant way?
If the dependence on the additional unknowns follows some pattern, then yes. For example, if the dependence on x(n) is x(n)^n then you can vectorize the above as,
x=x(:);
p1=x.^(1:n);
p2=x;
But as it stands, there is no apparent pattern in the dependence on x(i) nor on the coefficients a,b,c etc...
Torsten
on 7 Apr 2015
You can adopt the size of your system in the call to fsolve:
A=[a b;c d];
rhs=[-c;-c];
x0=[1;1];
x=fsolve(@(x)myfun(x,A,rhs),x0);
function F = myfun(x,A,rhs)
F = A*x-rhs;
Best wishes
Torsten.
1 Comment
Matt J
on 7 Apr 2015
Steve Stevens' comment moved here:
It works but there is a small problem I have noticed. Imagine in the first equation the unknowns are to the square and in the last two are not. So something like this:
a*x(2)^2+b*x(1)^2+c=0
c*x(2)+d*x(1)+c=0
e*x(2)+f*x(1)+c=0
How do I define this in myfunction?
Categories
Find more on Systems of Nonlinear Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!