Advertisement
makispaiktis

Optimization - Curve Fitting

Nov 1st, 2022 (edited)
1,086
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.58 KB | None | 0 0
  1. clear all
  2. close all
  3. clc
  4.  
  5.  
  6. %% Data
  7. % I want to fit data in the curve: c1 + c2*exp(-t)
  8. tic
  9. t = [0 0.3 0.8 1.1 1.6 2.3]';
  10. y = [0.82 0.72 0.63 0.60 0.55 0.50]';
  11.  
  12.  
  13. %% 1. Solution with / - Solver POV
  14. % We have 6 equations and 2 unknowns, so this should be infeasible
  15. % Matlab solves this system
  16. display('*************************************');
  17. display('1. Solution with mldivide');
  18. E = [ones(length(t), 1) exp(-t)];
  19. c = E\y;
  20. disp("c1 = " + num2str(c(1)) + ", c2 = " + num2str(c(2)))
  21. points(t, y);
  22. hold on
  23. check(c, 'red');
  24. title('y(t) = c_1 + c_2e^{-t} with mldivide');
  25. display('*************************************');
  26. display(' ');
  27.  
  28.  
  29. %% 2. Constrained Curve Fitting - Problem-based POV
  30. display('*************************************');
  31. display('2. Solution with optimproblem');
  32. display('and 1 extra constraint');
  33. p = optimproblem;
  34. x = optimvar('x', 2);
  35. p.ObjectiveSense = 'minimize';
  36. p.Objective = sum((E*x-y).^2);
  37. p.Constraints.intercept = x(1)+x(2) == 1.00 * y(1);
  38. sol = solve(p);
  39. c_constr = sol.x
  40. points(t, y);
  41. hold on
  42. check(c_constr, 'red');
  43. title('y(t) = c_1 + c_2e^{-t} with optimproblem');
  44. display('*************************************');
  45. display(' ');
  46.  
  47.  
  48. %% Comparing the methods
  49. points(t, y);
  50. hold on
  51. check(c, 'red');
  52. hold on
  53. check(c_constr, 'blue');
  54. legend("Data", "mldivide", "optimproblem")
  55.  
  56.  
  57.  
  58. function points(t, y)
  59.     figure();
  60.     plot(t, y, 'bo', 'Markersize', 10);
  61.     xlabel('Time');
  62.     ylabel('Response');
  63. end
  64.  
  65. function check(c, color)
  66.     tt = linspace(0, 2.5, 101);
  67.     yy = c(1) + c(2) * exp(-tt);
  68.     plot(tt, yy, color);
  69. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement