MATLAB: How to loop a objective function using the optimization toolbox

Optimization Toolboxoptmization toolbox loop

Hi everyone,
I have a question that how can I put a "loop" structure in a optmization problem.
In my problem I have two binary decision variables and a objective function based on these two variables, and I am trying to use optmization toolbox to minimize the objective function.
There are 4 time periods in total, and the binary decision variables are changing(differs) in each time period. My objective function is built on the decision variable so that the objective function is for one time period as well. My goal is to minimize my objective function over all time periods.
For example, I have two binary decision variabe "y" and "s" that differs in each time period,
for n=4 %4 years in total
t=1:n
y=optimvar('y',[4,1],'Type','integer','LowerBound',0,'UpperBound',1);%binary decision variable

s=optimvar('s',[4,1],'Type','integer','LowerBound',0,'UpperBound',1);%binary decision variable
obj=optimproblem
obj.Objective = 2y+3s %minimize 2y+3s
obj.Constraints.precedence=y(t)-y(t-1)>=0 % a precedence constraint about y
[sol,fval] = solve(obj) % maybe use other method, i am supposed to use simmulated annealing

Best Answer

My objective function is built on the decision variable so that the objective function is for one time period as well.
You cannot solve this as 4 separate problems, because your precedence constraint creates a dependence between y(t) and y(t-1). The following might be what you are looking for (and it doesn't require a loop):
y=optimvar('y',[4,1],'Type','integer','LowerBound',0,'UpperBound',1);%binary decision variable

s=optimvar('s',[4,1],'Type','integer','LowerBound',0,'UpperBound',1);%binary decision variable
obj=optimproblem;
obj.Objective = 2*sum(y)+3*sum(s); %minimize
obj.Constraints.precedence=diff(eye(4))*y>=0; % a precedence constraint about y
[sol,fval] = solve(obj)