Challenge

Week 3 - Solving second order ODEs

code :-

% inputs
% b = damping coefficient
% g = gravity, m/s^2
% l = length, meter
% m = mass, kg
b = 0.05;
g = 9.81;
l = 1;
m = 0.1;

% initial condition,
% initial displacement = 0
% initial velocity = 5 m/sec
theta_0 = [0;3];

% time points
% t_span is variation in the motion of pendulum
t_span = linspace(0,10,500);

% solve ODE
% ode45 is program solver in matlab
% ode_func is an seperate program use in these code via extension
[t,results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
plot(t,results(:,1),'color','g')
hold on
plot(t,results(:,2),'color','r')
hold on
subplot(5,4,[15,16,19,20]);
plot(results(:,1),results(:,2))
xlabel('position(in RADIAN)')
ylabel('Angular Velocity')

% To run a loop for different values of theta
ct = 1;
for i = 1:length(results(:,1))
    x0 = 0;
    y0 = 0;
    x1 = 1*sin(results(i,1));
    y1 = -1*cos(results(i,1));
    subplot(5,4,[1,2,3,4,5,6,7,8,9,10,11,12]);
    plot([1 1],[0 0],'Linewidth',4,'color','k');
    hold on
    line([x0 x1],[y0 y1],'linewidth',2,'color','b');
    hold on
    
    % making a marker shows a bob
    plot(x1,y1,'-o','markers',20,'markerfacecolor','r');
    
    grid on;
    axis([-1.5 1.5 -1.5 0.5])
    pause(0.0003);
    hold  off
    q(ct) = getframe(gcf);
    %text = sprintf("pendulum%d.png",ct);
    %saves(1,Text)
    ct = ct + 1;
end    

movie(q)
videofile = VideoWriter('pendulum_damped.avi','Uncompressed Avi');
open(videofile)
writevideo(videofile,q)
close(videofile)

function definition :-

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]

result :-

errors faced on programming :-

upper case 'Sin' and 'Cos' used instead of 'sin' and 'cos'

wrote '0' instead of 'o'

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.

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.