89 lines
1.9 KiB

  1. % === Problem 2b: Estimation using only q(t) and u(t) ===
  2. % True parameter values
  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
  11. data = readtable('problem1_data.csv');
  12. t = data.t;
  13. q = data.q;
  14. u = data.u;
  15. Ts = t(2) - t(1);
  16. N = length(t);
  17. % Compute dq and ddq using central differences
  18. dq = zeros(N, 1);
  19. ddq = zeros(N, 1);
  20. for k = 2:N-1
  21. dq(k) = (q(k+1) - q(k-1)) / (2 * Ts);
  22. ddq(k) = (q(k+1) - 2*q(k) + q(k-1)) / Ts^2;
  23. end
  24. % Build regression matrix and output vector
  25. X = [ddq, dq, q];
  26. y = u;
  27. % Least Squares estimation
  28. theta_hat = (X' * X) \ (X' * y);
  29. % Parameter extraction
  30. mL2_est = theta_hat(1);
  31. c_est = theta_hat(2);
  32. mgL_est = theta_hat(3);
  33. % Reconstruct ddq_hat from estimated parameters
  34. ddq_hat = (1 / mL2_est) * (u - c_est * dq - mgL_est * q);
  35. % Integrate to get dq_hat and q_hat
  36. dq_hat = zeros(N,1);
  37. q_hat = zeros(N,1);
  38. dq_hat(1) = dq(1);
  39. q_hat(1) = q(1);
  40. for k = 2:N
  41. dq_hat(k) = dq_hat(k-1) + Ts * ddq_hat(k-1);
  42. q_hat(k) = q_hat(k-1) + Ts * dq_hat(k-1);
  43. end
  44. % Estimation error
  45. e_q = q - q_hat;
  46. % === Plots ===
  47. figure('Name', 'Problem 2b - LS Estimation from q only', 'Position', [100, 100, 1280, 800]);
  48. subplot(3,1,1);
  49. plot(t, q, 'b', t, q_hat, 'r--');
  50. legend('q(t)', 'q̂(t)');
  51. title('Actual vs Estimated Angle from q(t) only');
  52. ylabel('Angle [rad]');
  53. grid on;
  54. subplot(3,1,2);
  55. plot(t, e_q, 'k');
  56. title('Estimation Error e_q(t) = q(t) - q̂(t)');
  57. ylabel('Error [rad]');
  58. grid on;
  59. subplot(3,1,3);
  60. bar(["mL^2", "c", "mgL"], theta_hat);
  61. title('Estimated Parameters');
  62. ylabel('Value');
  63. grid on;
  64. % Save figure
  65. saveas(gcf, 'Prob2b_20s_Ts0.1.png');
  66. % Print results
  67. fprintf(' Actual Parameters: mL^2=%f, c=%f, mgL=%f\n', theta_true(1), theta_true(2), theta_true(3));
  68. fprintf('Estimated Parameters: mL^2=%f, c=%f, mgL=%f\n', theta_hat(1), theta_hat(2), theta_hat(3));