Reputation: 81
I'm completely new to Matlab and I've been having some problems with my code.
I need to use 'fsolve' to locate minimizers to a nonlinear optimization problem, but I can't get it to work. I've been using the 'Solution Process of Nonlinear System' part from mathworks.
My code is the following:
function F = myfun(x)
F = [4*x(4) + 2*x(1) - x(3)*(2*x(1) + 4) + 4*x(1)*(x(1).^2 + x(2) - 11) + 2*x(2).^2 - 14;
x(3) - 10*x(4) + 2*x(2) + 4*x(2)*(x(2).^2 + x(1) - 7) + 2*x(1).^2 - 22;
x(2) - (x(1) + 2).^2;
4*x(1) - 10*x(2);];
x0 = [-5;-5];
options = optimoptions('fsolve','Display','iter');
[x,fval] = fsolve(@myfun,x0,options);
end
Where it says that; the value assigned to x appears to be unused as well as; not enough input arguments. But accoring to the mathworks page, I've done the exact same thing as them, so I'm sort of lost now.
Upvotes: 0
Views: 202
Reputation: 2575
There are several things that you are not doing correctly:
myfun
must only contain equations (as mentioned in Florian's comment).fsolve
, x0
and options
must be called from a separate script or from the Command Window.x0
must have at least as many elements as variables (x(4)
, x(3)
, x(2)
, x(1)
) present in the equations in myfun
.Edit your function myfun
, make sure that it only contains equations and save it in your working directory.
function F = myfun(x)
F = [4*x(4) + 2*x(1) - x(3)*(2*x(1) + 4) + 4*x(1)*(x(1)^2 + x(2) - 11) + 2*x(2)^2 - 14;
x(3) - 10*x(4) + 2*x(2) + 4*x(2)*(x(2)^2 + x(1) - 7) + 2*x(1)^2 - 22;
x(2) - (x(1) + 2)^2;
4*x(1) - 10*x(2)];
end
Note that you don't need to use the element-wise power operator .^
. Using the ^
operator will be enough to define powers in your equations.
Now in the Command Window enter the following instructions:
x0 = [-5;-5;-5;-5];
options = optimoptions('fsolve','Display','iter');
[x,fval] = fsolve(@myfun,x0,options);
Note that I modified x0
to have at least 4 elements in order to match the number of equations that you defined in myfun
. These are just sample values, so you should modify x0
with the values of your problem.
This is a fragment of the output:
Norm of First-order Trust-region
Iteration Func-count f(x) step optimality radius
0 5 81521 4.27e+04 1
1 10 12608.5 1 1.15e+04 1
2 15 966.243 2.5 1.71e+03 2.5
3 20 408.322 6.25 685 6.25
4 21 408.322 15.625 685 15.6
5 26 263.815 3.90625 244 3.91
6 27 263.815 9.76563 244 9.77
7 32 205.88 2.44141 272 2.44
8 37 138.11 6.10352 206 6.1
9 42 93.4561 6.10352 105 6.1
10 47 64.0129 6.10352 42.3 6.1
...
Upvotes: 1