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

 採用された回答

Torsten
Torsten 2022 年 11 月 6 日

1 投票

[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 件のコメント

BryanSz
BryanSz 2022 年 11 月 6 日
That worked, thanks!
Walter Roberson
Walter Roberson 2022 年 11 月 6 日
編集済み: Walter Roberson 2022 年 11 月 6 日
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

サインインしてコメントする。

その他の回答 (0 件)

製品

リリース

R2022a

タグ

質問済み:

2022 年 11 月 6 日

編集済み:

2022 年 11 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by