Errors with fmincon in Matlab script

I get these errors when I try to run my script. Any suggestions? The meshgrid section of code runs fine.
Not enough input arguments.
Error in HW5_fmincon>system2 (line 20)
x3 = 3*sin(x1.*x2)./(1+x1.^2);
Error in HW5_fmincon (line 12)
[x,fval] = fmincon(system2,[2;3.5],[],[],[],[],[1;2],[3;5])
------------------------------------------------------------------------------------------------------------------------------------------------
clear
clc
% Use fmincon to find the minimum values of x(1) and x(2) that will
% satisfy function system2 below
% Initial guess is x(1) = 2 and x(2) = 3.5
% Subject to the following constraints:
% 1<=x(1)<=3 and 2<=x(2)<=5
[x,fval] = fmincon(system2,[2;3.5],[],[],[],[],[1;2],[3;5])
% Create 3D plot using x(1) and x(2) between -4 and 4 in 0.2 increments
[a,b]=meshgrid(-4:0.2:4);
fx=system2(a,b);
mesh(a,b,fx)
function x3 = system2(x1,x2)
x3 = 3*sin(x1.*x2)./(1+x1.^2);
end

 Respuesta aceptada

Torsten
Torsten el 6 de Nov. de 2022
[x,fval] = fmincon(@(x)system2(x(1),x(2)),[2;3.5],[],[],[],[],[1;2],[3;5])
instead of
[x,fval] = fmincon(system2,[2;3.5],[],[],[],[],[1;2],[3;5])

2 comentarios

BryanSz
BryanSz el 6 de Nov. de 2022
That worked, thanks!
Walter Roberson
Walter Roberson el 6 de Nov. de 2022
Editada: Walter Roberson el 6 de Nov. de 2022
Your mesh extends outside the restrictions of your constraints. If you look only at the mesh points within the restrictions, the minima is not as good as fmincon finds.
% Use fmincon to find the minimum values of x(1) and x(2) that will
% satisfy function system2 below
% Initial guess is x(1) = 2 and x(2) = 3.5
% Subject to the following constraints:
% 1<=x(1)<=3 and 2<=x(2)<=5
[x,fval] = fmincon(@(x)system2(x(1),x(2)),[2;3.5],[],[],[],[],[1;2],[3;5])
Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
x = 2×1
1.0000 4.7124
fval = -1.5000
% Create 3D plot using x(1) and x(2) between -4 and 4 in 0.2 increments
[a,b]=meshgrid(-4:0.2:4);
fx=system2(a,b);
h = mesh(a,b,fx);
h.FaceAlpha = 0.2;
hold on
plot3(x(1), x(2), fval, 'r*')
mask = 1 <= a & a <= 3 & 2 <= b & b <= 5;
selected_values = fx(mask);
smallest_on_mesh = min(selected_values)
smallest_on_mesh = -1.2248
smallest_via_fmincon = fval
smallest_via_fmincon = -1.5000
smallest_outside_mesh = min(fx(~mask))
smallest_outside_mesh = -2.5851
function x3 = system2(x1,x2)
x3 = 3*sin(x1.*x2)./(1+x1.^2);
end

Iniciar sesión para comentar.

Más respuestas (0)

Productos

Versión

R2022a

Etiquetas

Preguntada:

el 6 de Nov. de 2022

Editada:

el 6 de Nov. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by