81 lines
2.0 KiB

  1. % === Problem 3b: Effect of Sampling Period Ts on Estimation Accuracy ===
  2. clear; close all;
  3. % True parameters
  4. m = 0.75;
  5. L = 1.25;
  6. c = 0.15;
  7. g = 9.81;
  8. mL2_true = m * L^2;
  9. mgL_true = m * g * L;
  10. theta_true = [mL2_true; c; mgL_true];
  11. % Parameters of input
  12. A0 = 4;
  13. omega = 2;
  14. % Time settings
  15. T_final = 20;
  16. dt = 1e-4;
  17. t_full = 0:dt:T_final;
  18. % Simulate system with very fine resolution
  19. odefun = @(t, x) [
  20. x(2);
  21. (1/(m*L^2)) * (A0*sin(omega*t) - c*x(2) - m*g*L*x(1))
  22. ];
  23. x0 = [0; 0];
  24. [t_sim, x_sim] = ode45(odefun, t_full, x0);
  25. % Sampling periods to test
  26. Ts_list = [0.01, 0.05, 0.1, 0.2, 0.5];
  27. n_cases = length(Ts_list);
  28. rel_errors_all = zeros(3, n_cases);
  29. for i = 1:n_cases
  30. Ts = Ts_list(i);
  31. % Resample at this Ts
  32. t_sampled = t_sim(1):Ts:t_sim(end);
  33. q = interp1(t_sim, x_sim(:,1), t_sampled);
  34. u = A0 * sin(omega * t_sampled);
  35. N = length(t_sampled);
  36. % Compute dq and ddq with central differences
  37. dq = zeros(N,1);
  38. ddq = zeros(N,1);
  39. for k = 2:N-1
  40. dq(k) = (q(k+1) - q(k-1)) / (2*Ts);
  41. ddq(k) = (q(k+1) - 2*q(k) + q(k-1)) / Ts^2;
  42. end
  43. % LS Estimation
  44. idx = 2:N-1; % Truncate to valid range (2:N-1)
  45. X = [ddq(idx), dq(idx), q(idx)'];
  46. y = u(idx).';
  47. theta_hat = (X' * X) \ (X' * y);
  48. rel_error = abs((theta_hat - theta_true) ./ theta_true) * 100;
  49. rel_errors_all(:, i) = rel_error;
  50. % Print
  51. fprintf('Ts = %.3f s → mL^2=%.4f (%.2f%%), c=%.4f (%.2f%%), mgL=%.4f (%.2f%%)\n', ...
  52. Ts, theta_hat(1), rel_error(1), ...
  53. theta_hat(2), rel_error(2), ...
  54. theta_hat(3), rel_error(3));
  55. end
  56. % === Plot ===
  57. figure('Name', 'Problem 3b - Effect of Sampling Period', 'Position', [100, 100, 1000, 600]);
  58. plot(Ts_list, rel_errors_all', '-o', 'LineWidth', 2, 'MarkerSize', 4);
  59. legend({'mL^2', 'c', 'mgL'}, 'Location', 'northwest');
  60. xlabel('Sampling Period Ts [sec]');
  61. ylabel('Relative Error [%]');
  62. title('Effect of Ts on Parameter Estimation');
  63. grid on;
  64. saveas(gcf, 'output/Prob3b_SamplingPeriodEffect.png');