Advertisement
makispaiktis

Course 3 - Solve the optimization problem (fminunc is used)

Aug 28th, 2023
1,238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.93 KB | None | 0 0
  1. clear all
  2. close all
  3. clc
  4.  
  5. % 1. Basics
  6. prob = optimproblem("Description","Factory Location");
  7. x = optimvar("x");
  8. y = optimvar("y");
  9. X = [5 40 70];
  10. Y = [20 50 15];
  11.  
  12. % 2. Optimization problem
  13. d = sqrt((x-X).^2 + (y-Y).^2);
  14. dTotal = sum(d);
  15. prob.Objective = dTotal;
  16. show(prob)
  17. initialGuess.x = 100;
  18. initialGuess.y = 200;
  19.  
  20. % 3. Solve the problem (MATLAB automatically decides the solver - here it is 'fminunc')
  21. [sol, optval] = solve(prob, initialGuess)
  22. xOpt = sol.x
  23. yOpt = sol.y
  24. optval2 = evaluate(dTotal, sol)
  25. vectors = evaluate(d, sol)
  26. flag = optval == optval2
  27.  
  28. % 4. Display
  29. plotStores
  30. hold on
  31. scatter(xOpt, yOpt, 'redX')
  32. hold off
  33.  
  34.  
  35.  
  36. function plotStores()
  37.    
  38.     X = [5 40 70];
  39.     Y = [20 50 15];
  40.     pgon1 = nsidedpoly(5,"Center",[X(1) Y(1)],"sidelength",3);
  41.     pgon2 = nsidedpoly(5,"Center",[X(2) Y(2)],"sidelength",3);
  42.     pgon3 = nsidedpoly(5,"Center",[X(3) Y(3)],"sidelength",3);
  43.     plot([pgon1 pgon2 pgon3])
  44.     axis equal
  45.  
  46. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement