80 lines
1.8 KiB

  1. % === Problem 2: Parameter Estimation using Least Squares ===
  2. % True data for comparison
  3. m = 0.75;
  4. L = 1.25;
  5. c_true = 0.15;
  6. g = 9.81;
  7. mL2_true = m * L^2;
  8. mgL_true = m * g * L;
  9. theta_true = [mL2_true; c_true; mgL_true];
  10. % Load sampled data from Problem 1
  11. data = readtable('output/problem1_data.csv');
  12. t = data.t;
  13. q = data.q;
  14. dq = data.dq;
  15. ddq = data.ddq;
  16. u = data.u;
  17. % Build regression matrix X and target vector y = u
  18. X = [ddq, dq, q]; % columns correspond to coefficients of [mL^2, c, mgL]
  19. y = u;
  20. % Least Squares estimation: theta_hat = [mL^2; c; mgL]
  21. theta_hat = (X' * X) \ (X' * y);
  22. % Extract individual parameters (optional interpretation)
  23. mL2_est = theta_hat(1);
  24. c_est = theta_hat(2);
  25. mgL_est = theta_hat(3);
  26. % Reconstruct ddq_hat using the estimated parameters
  27. ddq_hat = (1 / mL2_est) * (u - c_est * dq - mgL_est * q);
  28. % Numerical integration to recover dq̂(t) and q̂(t)
  29. Ts = t(2) - t(1);
  30. N = length(t);
  31. dq_hat = zeros(N,1);
  32. q_hat = zeros(N,1);
  33. % Initial conditions
  34. dq_hat(1) = dq(1);
  35. q_hat(1) = q(1);
  36. for k = 2:N
  37. dq_hat(k) = dq_hat(k-1) + Ts * ddq_hat(k-1);
  38. q_hat(k) = q_hat(k-1) + Ts * dq_hat(k-1);
  39. end
  40. % Estimation error
  41. e_q = q - q_hat;
  42. % === Plots ===
  43. figure('Name', 'Problem 2 - LS Estimation', 'Position', [100, 100, 1280, 800]);
  44. subplot(3,1,1);
  45. plot(t, q, 'b', t, q_hat, 'r--');
  46. legend('q(t)', 'q̂(t)');
  47. title('Actual vs Estimated Angle');
  48. ylabel('Angle [rad]');
  49. grid on;
  50. subplot(3,1,2);
  51. plot(t, e_q, 'k');
  52. title('Estimation Error e_q(t) = q(t) - q̂(t)');
  53. ylabel('Error [rad]');
  54. grid on;
  55. subplot(3,1,3);
  56. bar(["mL^2", "c", "mgL"], theta_hat);
  57. title('Estimated Parameters');
  58. ylabel('Value');
  59. grid on;
  60. saveas(gcf, 'output/Prob2_20s_Ts0.1.png');
  61. fprintf(' Actual Parameters: mL^2=%f, c=%f, mgL=%f\n', theta_true(1), theta_true(2), theta_true(3));
  62. fprintf('Estimated Parameters: mL^2=%f, c=%f, mgL=%f\n', theta_hat(1), theta_hat(2), theta_hat(3));