| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- % Enormous portions of this code were borrowed from code written while
- % following along in class.
- clc; clear all; close all;
- % Constants
- g = 9.81;
- L = 1;
- F0 = 10;
- c = 0.5;
- m = 1;
- initial_angle = deg2rad(70);
- initial_v = 0;
- initial_conditions = [initial_angle, initial_v];
- t_span = [0 100];
- % Driving frequencies for each test:
- omega1 = 1;
- omega2 = 1.9;
- % Setting up my ODE vectors manually again
- ode_system1 = @(t, theta) [
- theta(2); % dtheta/dt
- (F0*cos(omega1*t) - m*g*L*sin(theta(1)) - c*theta(2))/(m*L^2) % dtheta2/d2t
- ];
- ode_system2 = @(t, theta) [
- theta(2); % dtheta/dt
- (F0*cos(omega2*t) - m*g*L*sin(theta(1)) - c*theta(2))/(m*L^2) % dtheta2/d2t
- ];
- % Test 1, using omega1
- [t1, theta1] = ode45(ode_system1, t_span, initial_conditions);
- theta_sol1 = theta1(:, 1);
- dthetadt_sol1 = theta1(:, 2);
- f1 = figure;
- ax1 = axes(f1);
- plot(ax1, t1, theta_sol1);
- title(ax1, sprintf("Test 1, using initial angle %.0f deg and driving freq %.0f rad/s", initial_angle, omega1));
- xlabel(ax1, "Time (s)");
- ylabel(ax1, "Theta (rad)");
- % Test 2, using omega2
- [t2, theta2] = ode45(ode_system2, t_span, initial_conditions);
- theta_sol2 = theta2(:, 1);
- dthetadt_sol2 = theta2(:, 2);
- f2 = figure;
- ax2 = axes(f2);
- plot(ax2, t2, theta_sol2);
- title(ax2, sprintf("Test 2, using initial angle %.0f deg and driving freq %.0f rad/s", initial_angle, omega2));
- xlabel(ax2, "Time (s)");
- ylabel(ax2, "Theta (rad)");
- %-------------------------------------------------
- % Pendulum's base position
- x0 = 0; y0 = 0;
- % Animation loop
- f3 = figure;
- ax3 = axes(f3);
- axis equal;
- xlim(ax3, [-L, L]);
- ylim(ax3, [-L, 0.5]);
- xlabel(ax3, 'x (m)');
- ylabel(ax3, 'y (m)');
- % We're using test 2 results for the animation
- % Gotta render one frame first to get handles for the plots
- x = x0 + L*sin(theta_sol2(1));
- y = y0 - L*cos(theta_sol2(1));
- hold on;
- plot_string = plot(ax3, [x0,x], [y0,y], 'k-', 'LineWidth', 2);
- plot_ball = plot(ax3, x, y, 'ro', 'MarkerSize', 20);
- for i = 1:length(t2)
- % Update title
- title(ax3, sprintf("Pendulum Animation (Initial Angle = %.0f deg)\nTheta = %f\nTime = %f",...
- rad2deg(initial_angle),...
- theta_sol2(i),...
- t2(i)...
- ), 'FontSize',12);
- % Update pendulum position
- x = x0 + L*sin(theta_sol2(i));
- y = y0 - L*cos(theta_sol2(i));
- hold on;
- set(plot_string, 'XData', [x0,x], 'YData', [y0,y]);
- set(plot_ball, 'XData', x, 'YData', y);
- drawnow;
- pause(0.05);
- end
|