Question about FMINCON in optimization

1 次查看(过去 30 天)
Hi, I got a problem in fmincon in the nonlinear constrained optimization problem. Both target and constrain functions are integral functions. So I named four functions to make it clear.
The function is to optimize a -- a 10x1 array. l is a constant, and x is the variable to be integrated.
The problem is that when I call the fmincon, the function returns an error saying fmincon requires all values returned by functions to be of data type double.
I guess this probablly related to the intefral that I used. But I have no idea how to fix that.
Please help me out, thank you.
clc;clear;
a0 = ones(10,1);
l = 100;
seriesNum = 1;
syms x
% Pass fixed parameters to objfun
objfun3 = @(a)objectiveFcn(l,a);
% Set nondefault solver options
options3 = optimoptions('fmincon','PlotFcn','optimplotfvalconstr');
% Solve
[solution,objectiveValue] = fmincon(objfun3,a0,[],[],[],[],[],[],...
@constraintFcn,options3);
% Clear variables
clearvars objfun3 options3
% Functions
function f = divsurf(x,l,a,seriesNum)
fi0 = 3;
f = 1/l*(-fi0);
for i = 1:seriesNum
f = f + a(i)*i*pi/l*cos(i*pi*x/l);
end
f = f^2;
end
function f = surf(x,l,a,seriesNum)
% f = a*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
fi0 = 3;
f = fi0;
for i = 1:seriesNum
f = f + x / l * (-fi0) + a(i)*sin(i*pi*x/l);
end
end
% The following code creates the objective function. Modify this code for your problem.
function f = objectiveFcn(l,a)
% f = a*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
% l = 100;
syms x
seriesNum = 10;
f = int( @(x)divsurf(x,l,a,seriesNum),x,0,l);
end
% The following code creates the constraint function. Modify this code for your problem.
function [c,ceq] = constraintFcn(a)
lout = 10;
seriesNum = 10;
l = 100;
syms x
% c(1) = x(1)^2 + x(2)^2 - 5;
% c(2) = 3 - x(1)^2 - x(2)^2;
c(1) = int(@(x)surf(x,l,a,seriesNum),x,0,l)-lout;
ceq = []; % No equality constraints
end

采纳的回答

Matt J
Matt J 2022-10-21
编辑:Matt J 2022-10-22
You shouldn't be using syms, or at least you need to at some point convert your sym expressions as actual numbers. Anything generated by manipulating sym variables will not be a number, e.g.,
syms x
y=int(x.^2,0,1)
y = 
isa(y,'double')
ans = logical
0
You should probably be integrating numerically, using integral:
y=integral(@(x) x.^2 ,0,1)
y = 0.3333
isa(y,'double')
ans = logical
1
  3 个评论
Matt J
Matt J 2022-10-22
编辑:Matt J 2022-10-22
I don't see anything in your current constraint function that requires Symbolic Math. Why not as follows?
function [c,ceq] = constraintFcn(a)
lout = 10;
seriesNum = 10;
l = 100;
c = integral(@(x)surf(x,l,a,seriesNum),x,0,l)-lout;
ceq = []; % No equality constraints
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with Optimization Toolbox 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by