Advertisement
makispaiktis

Optimization - Linear - linprog, CVX

Oct 31st, 2022 (edited)
1,299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.16 KB | None | 0 0
  1. clear all
  2. close all
  3. clc
  4.  
  5. %% Linprog for: min(2x_1 + x_2)
  6. display('***********************************');
  7. display('linprog');
  8. f = [2 1];
  9. A = [-1 1; -1 -1; 0 -1; 1 -2];
  10. b = [1 -2 0 4]';
  11. [x_optimal, f_min] = linprog(f, A, b)
  12. display('***********************************');
  13. display(' ');
  14.  
  15.  
  16. %% CVX for: min(2x_1 + x_2)
  17. display('***********************************');
  18. display('CVX');
  19. cvx_begin quiet
  20.     variable x(2);
  21.     minimize(f*x);
  22.     subject to
  23.         A*x <= b;
  24. cvx_end
  25. disp("cvx_optval = " + num2str(cvx_optval));
  26. display('***********************************');
  27. display(' ');
  28.  
  29.  
  30. %% Plot
  31. figure();
  32. num_of_constr = size(A, 1);
  33. x = linspace(0, 1, 1001);
  34. y = linspace(0, 3, 1001);
  35. legends = [];
  36. for i = 1 : num_of_constr
  37.     z_constr = A(i, 1)*x + A(i, 2)*y;
  38.     plot3(x, y, z_constr, 'red');
  39.     str = "Constraint " + num2str(i);
  40.     legends = [legends str];
  41.     hold on
  42. end
  43. z_obj = f(1)*x + f(2)*y;
  44. plot3(x, y, z_obj, 'blue');
  45. hold on
  46. plot3(x_optimal(1), x_optimal(2), f_min, 'gx', 'Markersize', 10);
  47. legends = [legends "Objective Function" "Optimal Value"];
  48. title("Linprog");
  49. xlabel("x");
  50. ylabel("y");
  51. zlabel("z");
  52. legend(legends);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement