Challenge

Week 4.1 - Solving second order ODEs

Explanation Of this Code:

1. The initial part of the code clears some variables and closes any open figures, providing a clean workspace to work with.

2. The input variables b, g, l, and m are defined for the second-order ODE that represents the simple pendulum.

3. The initial conditions θ0 and the time span tspan are set for the simulation.

4. The ode45 function is used to solve the second-order ODE by calling the odefunc function, which defines the equations of motion for the simple pendulum. The solution is obtained in the variables t and rest–s.

5. A new figure (figure(1)) is created for plotting the angular velocity and displacement of the pendulum using plot commands.

6. The angles (∠) are extracted from the rest–s variable.

7. A counter variable ct is initialized to keep track of the iterations.

8. A folder named 'pendu––mames'

is created to store the individual frames of the animation. If the folder already exists, the mkdir command will not create it again.

9. A loop is used to iterate over each angle in the ∠variable.

10. Inside the loop, the moving coordinates of the pendulum bob are calculated based on the current angle (ω).

11. The motion of the pendulum is visualized by plotting the pendulum and the bob using plot commands.

12. The animation is paused for 0.1 seconds using the pause command to control the speed of the animation.

13. The current frame is captured using M(ct)=≥tame(gcf) and saved as a PNG image using the imwrite command. The frame is saved with a file name in the format example.png, where #### represents a four-digit frame number.

14. The counter ct is incremented for the next iteration.

15. After the loop finishes, the MATLAB script calls Python using the system command to convert the PNG images in the 'pendulam_simulation' folder into a GIF file. The Python code uses the ima≥io library to convert the images. Note that the ima≥io library needs to be installed in your Python environment.

16. The odefunc function defines the ODE equations for the simple pendulum. It takes the time t, the current state vector θ, and the parameters b, g, l, and m. The function calculates the derivatives of θ and returns them in dthηdt.That's a detailed explanation of the code. It simulates the motion of a simple pendulum, saves individual frames as PNG images, and then converts them into a GIF file using Python's ima≥io library.

Code:

clear theta1 theta2 dtheta1_dt dtheta2_dt
close all
clc

% input variables for the second-order ODE of a simple pendulum
b = 0.05;
g = 9.81;
l = 1;
m = 0.1;

theta_0 = [0; 3];

t_span = linspace(0, 20, 500);

% ode45 function to solve second-order ODE
[t, results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m), t_span, theta_0 );

% plotting of angular velocity and displacement
figure(1)
plot(t, results(:,1))
hold on
plot(t, results(:,2))
grid on
title('Motion of Pendulum')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/s) / Displacement (rad)')
legend('Displacement','Angular Velocity')

angle = results(:,1);

% count command for iterations.
ct = 1;

% Create a folder to store the PNG images
foldername = 'pendulum_frames';
if ~exist(foldername, 'dir')
    mkdir(foldername);
end

for i = 1 : length(angle)
    omega = angle(i);
    figure(2)
    title('Motion of Pendulum')
    
    % fixed coordinates of one end of the simple pendulum.
    x0 = 0;
    y0 = 0;
    
    % moving coordinates of the bob.
    x1 = l*cos((3*pi/2)+omega);
    y1 = l*sin((3*pi/2)+omega);
    
    % plotting of the bob motion.
    plot([x0 x1],[y0 y1],'linewidth',3,'color','g');
    hold on;
    plot(x1,y1,'o','MarkerSize',15,'MarkerFaceColor','k');
    hold on;
    plot([-3 3],[0 0],'linewidth',2,'color','b','MarkerSize',15);
    hold off
    axis([-3 3 -2 2])
    grid on 
    pause(0.1)
    M(ct) = getframe(gcf);
    
    % Save each frame as a PNG image
    framefilename = sprintf('%s/frame_%04d.png', foldername, ct);
    imwrite(M(ct).cdata, framefilename);
    
    ct = ct + 1;
end

% Use imageio library in Python to convert the PNG images into a GIF file
system(sprintf('python -m imageio.plugins.ffmpeg.download --path "%s"', matlabroot));  % Download imageio FFMpeg plugin if needed
system(sprintf('python -m imageio --output "%s/pendulum_animation.gif" "%s/*.png"', foldername, foldername));  % Convert PNG images to GIF

function [dtheta_dt] = ode_func(t,theta,b,g,l,m)
    theta1 = theta(1);
    theta2 = theta(2);
    dtheta1_dt = theta(2);
    dtheta2_dt = -(b/m)*theta2 - (g/l)*sin(theta1);
    dtheta_dt = [dtheta1_dt; dtheta2_dt];
end

Scope of the outputs:

Error Message:

CONCLUSION:

  • We have animated the simple pendulum using the ode45 solver where the second order is reduced to a simple differential equation where it is easy to solve the given equation.
  • The animation is made using the different points of the bob and the motion of the simple pendulum is created

Youtube Link:

https://youtu.be/mSH-Jyi2m3M

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.