Using fsolve to determine roots of a simultaneous nonlinear equation.
6 views (last 30 days)
Show older comments
3 Comments
Answers (2)
John D'Errico
on 1 Oct 2015
Edited: John D'Errico
on 1 Oct 2015
Close. But no cigar. A good start though.
Effectively, the way you have posed it, fsolve will attempt to solve the equations
x^2 + 1 == 0
3*cos(x) == 0
Fsolve tries to set the expressions it sees equal to ZERO. But your problem has y in it, as an unknown. These are SIMULTANEOUS equations, two of them, in two unknowns. Here, the unknowns are x and y in those original equations.
The equations are better written in the form that fsolve wants to see them, as:
x^2 + 1 - y = 0
3*cos(x) - y = 0
fsolve will need a vector of starting values, with the two unknowns in a vector. So your function will look like this:
myfun = @(xy) [xy(1)^2 + 1 - xy(2); 3*cos(xy(1)) - xy(2)];
xy0 = [.5 .5]; % guess
[xy,fval,exitflag] = fsolve(myfun,xy0)
Equation solved.
fsolve completed because the vector of function values is near zero
as measured by the default value of the function tolerance, and
the problem appears regular as measured by the gradient.
<stopping criteria details>
xy =
0.91313 1.8338
fval =
1.2947e-08
-1.1871e-08
exitflag =
1
Fsolve thinks this was a success. And if you want to use an m-file function, it might look like this:
function obj = myfun(xy)
obj = [xy(1)^2 + 1 - xy(2); 3*cos(xy(1)) - xy(2)];
end
Personally, the function handle is far simpler to write. No file needed to be saved. Shorter.
Finally, we can solve this particular problem more simply yet, if we recognize that y can be eliminated. The pair of equations are equivalent to:
x^2 + 1 = 3*cos(x)
Solve this, using fzero most simply, since it is one equation in one unknown.
xfun = @(x) x.^2 + 1 - 3*cos(x);
x = fzero(xfun,1)
x =
0.91313
Now, recover y. See that we get the same value for each expression, as expected.
y = x^2 + 1
y =
1.8338
3*cos(x)
ans =
1.8338
0 Comments
Star Strider
on 1 Oct 2015
I’m not sure where you’re getting the ‘unexpected MATLAB operator’ error.
Running this code in a script file works:
myfun = @(x) [x.^2+1; 3*cos(x);];
x0=[5]
fsolve(myfun,x0)
although you don’t need the second semicolon (after the second expression) here: [x.^2+1; 3*cos(x);], that won’t throw the error.
2 Comments
John D'Errico
on 1 Oct 2015
But that is not actually the system of equations. Don't forget that y is an unknown.
See Also
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!