Challenge

Week 3 - Solving second order ODEs using MATLAB

the project was started off using the same basic code as the one used in 2R robot challenge.

the code takes initial values defined in the code below and then uses a custom function created (Odefun.m) to define the ordinary differential equation and the relation between the initial values and the time and result values.

the following plot is created with the initial code.

that function is used in the built-in ODE45 function to solve the function and assign the values. we then start a loop to differentiate the individual frames of the plot. inside the loop we define the x and y cordinates of the function in terms of the 'result' that we found using our ode45 function.

we use this to create a plot and then we use the marker command to form a sphere at the end on the pendulum.

while execution the following errors were faced:

the error was in running the ode45 command as the values of the theta matrix had an issue which was resolved.

the second error was faced with the animation because according to the command window a struct can't be converted into a double i.e. 'm' variable can't take multiple values because the plots are different for the function. the issue was resolved by assigning the frame value to a single variable m which was then assigned to 'v(ct)' which captures each value of 'm' which itself takes each individual frame in every iteration.

the code was uploaded to youtube and the link for the same is:

https://youtu.be/YEESYyvXm_A

the code has also been uploaded to github and the link for the same has been mentioned in the description of the video on youtube.

%simulate the motion of a pendulum
clear all
close all
clc
%initial values
l=1;
m=1;
b=0.05;
g=9.81;

%theta values
q=[0;3];
t=linspace(0,20,200);
%solve
[time,result]=ode45(@(t,q) odefun(t,q,b,g,l,m),t,q);

%plot

t=1;
for i =1:length(result)
    a=result(i);
    x1=l+l*cos((3*pi/2)+a)
    y1=l+l*sin((3*pi/2)+a)
    plot([l x1],[l y1],'-o','linewidth',1.5,'color',[0 0 0],'markerfacecolor','r','markersize',10)
    axis([0 2 0 2])
    pause(0.25)
    m=getframe(gcf);
    c(t)=m;
    t=t+1;
end
movie(c)
video = VideoWriter('Pendulum.avi','Uncompressed AVI')
open(video)
writeVideo(video,c)
close(video)
------------------------------------------------------------------------------------------------------------------


function [dtheta_dt]= odefun(t,q,b,g,l,m)
theta1=q(1)
theta2=q(2)
first=theta2;
second=(-b/m)*theta2 - (g/l)*sin(theta1);
dtheta_dt=[first;second]

end
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.