Advertisement
makispaiktis

Course 5 - Solve with constraints

Aug 28th, 2023 (edited)
1,263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.81 KB | None | 0 0
  1. clear all
  2. close all
  3. clc
  4.  
  5. % 1. Load the dataset
  6. load Nutrition.mat
  7. food
  8.  
  9. % 2. Create the optimization problem
  10. prob = optimproblem("Description","An Optimal Breakfast");
  11. servings = optimvar("servings",16,"LowerBound",0);
  12. C = food.Price .* servings;
  13. prob.Objective = sum(C);
  14.  
  15.  
  16. % 3. Equality constraint
  17. cals = servings .* food.Calories
  18. totalCals = sum(cals)
  19. prob.Constraints.calories = totalCals == 350
  20.  
  21. % 4. Solve the problem
  22. [sol, optval] = solve(prob)
  23. optServings = sol.servings
  24. check = evaluate(totalCals, sol)
  25.  
  26. % 5. Visualize the solution and explain
  27. bar(food.Name, optServings)
  28. % Since we are looking for 350 calories, but as cheap as possible, then
  29. % the output solution must have the biggest ratio calories / money
  30. caloriesPerDollar = food.Calories ./ food.Price;
  31. bar(food.Name, caloriesPerDollar)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement