higher_order_odes.m 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. % 1. Clear the workspace and figures
  2. clear; clc; close all;
  3. % 2. Define the differential equation system
  4. % The solver expects a function with inputs (t, Y) where Y is a vector:
  5. % Y(1) represents y, and Y(2) represents dy/dt.
  6. ode_system = @(t, Y) [
  7. Y(2); % dY1/dt = Y2
  8. Y(3); % dY2/dt = Y3
  9. -3*Y(3)-(1-Y(1)^2)*Y(2)+Y(1) % dY3/dt =
  10. ];
  11. % 3. Set the time span for simulation [start_time, end_time]
  12. t_span = [0, 5];
  13. % 4. Define initial conditions: [initial_y, initial_dydt]
  14. % For example: y(0) = 0.5 and dy/dt(0) = 0.0
  15. initial_conditions = [0.5; 0.0; 0];
  16. % 5. Solve the system numerically using ode45
  17. [t, Y] = ode45(ode_system, t_span, initial_conditions);
  18. % 6. Extract the individual states from the solution matrix
  19. y_sol = Y(:, 1); % First column is y(t)
  20. dydt_sol = Y(:, 2); % Second column is dy/dt(t)
  21. d2ydt2_sol = Y(:, 3); % Third column is d2y/dt2(t)
  22. % 7. Plot the results
  23. figure;
  24. plot(t, y_sol, '-b', 'LineWidth', 2);
  25. hold on;
  26. plot(t, dydt_sol, '--r', 'LineWidth', 1.5);
  27. grid on;
  28. % Labeling the graph
  29. title('Numerical Solution of Higher-Order ODE');
  30. xlabel('Time (t)');
  31. ylabel('State Values');
  32. legend('y(t) (Position)', 'dy/dt (Velocity)', 'Location', 'best');