Challenge

Week 3 - Solving second order ODEs

%ode_function code
%using x as theta and xdot as output variable of function
function xdot=ode_func(t,x)
%given values
b=0.05;
g=9.81;
l=1;
m=1;
%defining theta1 and theta2
xdot=zeros(2,1); % assign null matrix to xdot
xdot(1)=x(2); %this is 1st order ODE
xdot(2)=(-b/m)*x(2)-(g/l)*sin(x(1)); %this is 2nd order ODE

end

%ODE_main function code
clear all
close all
clc
%initial conditions
l=1;
x0=[0 3]; % zero is displacement and 3 is velocity
%time points
t=linspace(0,20,150);
% solving differential equation using ODE45 inbuilt solver in matlab
[t x]=ode45('ode_func',t,x0);
%plotting of angular velocity and angular displacement
plot(t,x(:,1))
hold on
plot(t,x(:,2))
xlabel('time');
ylabel('plot');
grid on;
%Animation to create a simple pendulum
X0=0;
Y0=0;
ct=1; %counter represnts each and every frame
for i=1:length(t)
X1=l*sin(x(i,1));
Y1=-l*cos(x(i,1));
figure(2)
plot([-1,1],[0,0],'linewidth',6,'color','g');
axis([-2 2 -2 2])
line([X0,X1],[Y0,Y1],'linewidth',3,'color','b');
hold on;
plot(X0,Y0,'O','markersize',3,'markerfacecolor','y');
plot(X1,Y1,'O','markersize',20,'markerfacecolor','r');
title('simple pendulum');
legend('supportrod','length of pendulum','fixed point','pendulum bod');
grid on;
hold off;
M(ct)=getframe(gcf);
ct=ct+1;
end
movie(M); %to create a movie of the oscillations
videofile=VideoWriter('simple pendulum','Uncompressed AVI');
open(videofile);
writeVideo(videofile,M);
close(videofile);

Errors:I have faced many errors while writing the code such as errors like semicoluns ,commas and also capital letters.There are few errors in the animation part like videowriter ,i was recommended to use VideoWriter instead.I have overcome all the errors using help option in the command window.

As the animated movie video is so large i couldnt upload it i am uploading the video on youtube and sharing you the link.Thankyou.

https://youtu.be/FJc9--cpQFQ

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.