Open this Example

Create Indexed Constraints in Loop

Create indexed constraints and variables to represent the calories consumed in a diet. Each meal has a different calorie limit.

meals = ["breakfast","lunch","dinner"];
constr = optimconstr(meals);
foods = ["cereal","oatmeal","yogurt","peanut butter sandwich","pizza","hamburger",...
    "salad","steak","casserole","ice cream"];
diet = optimvar('diet',foods,meals,'LowerBound',0);
calories = [200,175,150,450,350,800,150,650,350,300]';
for i = 1:3
    constr(i) = diet(:,i)'*calories <= 250*i;
end

Check the constraint for dinner.

showconstr(constr("dinner"))
200*diet('cereal', 'dinner') + 175*diet('oatmeal', 'dinner') +
150*diet('yogurt', 'dinner') + 450*diet('peanut butter sandwich', 'dinner') +
350*diet('pizza', 'dinner') + 800*diet('hamburger', 'dinner') +
150*diet('salad', 'dinner') + 650*diet('steak', 'dinner') +
350*diet('casserole', 'dinner') + 300*diet('ice cream', 'dinner') <= 750