Week 3 - Solving second order ODEs
- OBJECTIVE:- Write a program in Matlab\Octave that will simulate the pendulum motion, just like the one shown in the start of this challenge.
- Solution:-

In the last challenge, we had to make animation for the working kinematic arm with the same concept in mind we have to solve this challenge lets start with the code
clear
close all
clc
% Inputs
b = 0.05; % Damping force
M = 1; % Mass
g = 9.81; % gravity
l = 1; % lengh
% Initial Condition
theta_0 = [0,3];
% Time points
t_span = linspace(0,20,500);
% Solving the ODE
[t,r] = ode45(@(t,theta)ode_fun(t,theta,b,g,l,M),t_span,theta_0);
h = figure(1);
subplot(2,1,1)
plot(t,r(:,1),'m');
grid on; hold on;
plot(t,r(:,2),'r');
xlabel('time');
ylabel('displacment');
theta = r(:,1);
ct = 1;
videofile = VideoWriter('Pendulum.avi','uncompressed AVI');
open(videofile)
for i = 1:length(theta)
T = theta(i);
xo = 0;
yo = 0;
xb = l*sin(T);
yb = -l*cos(T);
subplot(2,1,2);
plot([-1 1],[0 0],'linewidth',2,'color','k');
hold on;
plot([xo,xb],[yo,yb],'linewidth',2,'color','b');
plot(xb,yb,'-o','markers',20,'markerfacecolor','r');
grid on;hold off
axis([-3 3 -1.5 .5]);
pause(0.03)
M = getframe(h);
writeVideo(videofile,M);
end
close(videofile)
we already have the required parameters for solving the problem. First, we give inputs like g = gravity in m/s2, L = length of the pendulum in m, m = mass of the ball in kg, b=damping coefficient with initial condition and time span values. To solve the eq we have to use ODE45 function and create another function which is solving the equation, After providing the inputs we have to plot the values of output to see the angular velocity and displacement after that, we have to create a FOR loop so that we can have multiple values of theta and we can create the animation, all we have to do is to merge every plot of theta value in one, it can be done by using the Movie command present in Matlab to do that first we have to create video file in AVI and accurate file name to the code by videofile commande then with getframe command we can stitch the images of output, The code for calling the function is given below
function [dtheta_dt] = ode_fun(t,theta,b,g,l,m)
theta1 = theta(1);
theta2 = theta(2);
dtheta1_dt = theta2;
dtheta2_dt = -(b/m)*theta2-(g/l)*sin(theta1);
dtheta_dt = [dtheta1_dt;dtheta2_dt];
end
In this, we have to give inputs and specify the main theta values which are 2-D equation as, input and will have an output as time derivative term
Here is the link to the animation
Error:-
:-
with this error, other errors which I faced were the small small typing mistakes which I don't consider mentioning herein the above code it shows the struct is not possible because the conversion will not happen if it is provided with two inputs as we only need the displacement values for the animation we have to take the first column which has displacement values and then this values must be assigned to a variable the use it in the loop.