How can I include a function in a for loop for an optimization problem?

I have an optimization problem which should minimize b(i)*h(i)*100 for i=1:5 considering 5 inequality constraints. Since I need to write two functions; "function f = objfun(b,h)" and "function [c, ceq] = confun(x)" I am having hard time placing the for loop i=1:5 in the code which I aim to sum up all the b(i)*h(i)*100 values at the end. Below is the code I wrote, any kind of help is appreciated.
function f = objfun(b,h)
for i=1:5
vol=b(i)*h(i)*100;
f=sum(vol(1:i));
P=50000;
L=500;
le(i)=100;
dy(0)=0;
y(0)=0;
x0=[40,5];
y(i)=(P*((le(i))^2)/2*E*in(i))*[L-sum(le(1:i))+2*le(i)/3]+dy(i-1)+y(i-1);
dy(i)=(P*l(i)/E*in(i))*[L+l(i)/2-sum(le(1:i))]+dy(i-1);
in(i)=(b(i)*h(i)^3)/12;
M(i)=p*[L+le(i)-sum(le(1:i))];
sig(i)=M(i)*h(i)/2*in(i);
function [c, ceq] = confun(x)
c=[sig(i)-14000;
y(5)-2,5;
h(i)-20*(b(i));
1-b(i);
5-h(i)];
ceq=[];
options=optimoptions(@fmincon, 'Algorithm','sqp');
z(i)=fmincon(@objfun,x0,[],[],[],[],[],@confun,options);
z(0)=0;
z(i)=z(i)+z(i-1);
end
end
z(5)
[c]=confun(z(5))
Thanks!

回答 (1 件)

Alan Weiss
Alan Weiss 2016 年 12 月 1 日
If I understand you, you have five different problems that you are trying to solve. You need to solve them one at a time. The for loop does not belong inside your objective or constraint function.
Additionally, you need to pass b and h, your variables that I think you are optimizing, in one vector or matrix, usually called x, bur for you I'll call it bh. I don't know if bh is a 2-element vector or is a 10-element matrix or what, so my code which assumes that it is a 2-element vector might be incorrect.
You should have your objective function depend only on i, the index of the problem you are solving. Same for your nonlinear constraint function. Something like this:
function f = objfun(bh,i)
b = bh(1);
h = bh(2);
%Write your objective function in terms of i here
end
function [c,ceq] = confun(bh,i)
b = bh(1);
h = bh(2);
%Write your constraint function in terms of i here
end
After this, for each i you set your objective function to @(bh)objfun(bh,i) and likewise your constraint function to @(bh)confun(bh,i).
Alan Weiss
MATLAB mathematical toolbox documentation

2 件のコメント

Tarami Readus
Tarami Readus 2019 年 7 月 2 日
What does ceq mean?
Walter Roberson
Walter Roberson 2019 年 7 月 2 日
ceq is for Nonlinear Equality Constraints. c is for Nonlinear Inequality Constraints.

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

カテゴリ

質問済み:

2016 年 12 月 1 日

コメント済み:

2019 年 7 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by