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];
[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:
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