Differential Equation MatLab 2 due in 5 hours
function springmass(p,omega0,y0,v0,tf)
%springmass(p,omega0,y0,v0,tf,omega) solves the damped harmonic problems
% y'' + 2 p y' + omega0^2 y = 0
% with y(t=0)=y0, y'(t=0)=v0 from t=0 to tf using fourth-order Runge-Kutta
t0 = 0;
tspan = [t0 tf];
w0 = [y0; v0];
opts = odeset('RelTol',10^-9,'AbsTol',10^-12);
[t,w] = ode45(@f,tspan,w0,opts);
figure
plot(t,w(:,1),'b-')
xlabel('t','FontSize',16)
ylabel('y','FontSize',16)
xlim([t0 tf])
function wprime = f(t,w)
wprime = [w(2); -omega0^2*w(1)-2*p*w(2)];
end
end
function springmassdriven(p,omega0,y0,v0,tf,omega)
%springmassdriven(p,omega0,y0,v0,tf,omega) solves the forced damped
%harmonic problems
% y'' + 2 p y' + omega0^2 y = cos(omega t)
% with y(t=0)=y0, y'(t=0)=v0 from t=0 to tf using fourth-order Runge-Kutta
t0 = 0;
tspan = [t0 tf];
w0 = [y0; v0];
opts = odeset('RelTol',10^-9,'AbsTol',10^-12);
[t,w] = ode45(@f,tspan,w0,opts);
figure
plot(t,w(:,1),'b-')
xlabel('t','FontSize',16)
ylabel('y','FontSize',16)
xlim([t0 tf])
function wprime = f(t,w)
wprime = [w(2); -omega0^2*w(1)-2*p*w(2)+cos(omega*t)];
end