Runge-Kutta solving 2nd ODE
Show older comments
Hey guys, given that y''+3y'+2y=2e^(-3t), with y(0)=0,y'(0)=1.
let x1=y, x2=y'
dx1=y'=x2------->(1)
dx2=y''=2e^(3t)-3x2-2x1------->(2)
but there's somethings confusing me, what should i write for F1 since it doesn't have idea what it y'.
I'm new to MATLAB, so i really have no idea what i'm doing.
my TA ask me what is y' but i have no idea what i'm gonna tell him what's y'.
function RungeKuttaMethod
a = 0; %time interval we are solving over
b = 4;
N = 1000; %number of steps
%t = zeros(1, N);
%y = zeros(1, N);
%y(0) = 0; %initial value of y.
%y'(0) = 1; %initial value of y'.
h = (b - a)/N; %step size
F1 = @(t,y)y' ;
F2 = @(t, y)2*exp(-3*t)-3*y'-2*y; %thing we are solving.
for i = 1:(N-1)
K11 = h*(F1(t(i),y(i)));
K21 = h*(F2(t(i), y(i)));
K12 = h*(F1(t(i)+0.5*h,y(i)+0.5*K21));
K22 = h*(F2(t(i) + 0.5*h, y(i) + 0.5*K11));
K13 = h*(F1(t(i)+0.5*h,y(i)+0.5*K22));
K23 = h*(F2(t(i) + 0.5*h, y(i) + 0.5*K12));
K14 = h*(F1(t(i)+h,y(i)+K22));
K24 = h*(F2(t(i) + h, y(i) + K13));
y1(i+1) = y(i) + (K11 + 2*K12 + 2*K13 + K14)/6;
y2(i+1) = y(i) + (K21 + 2*K22 + 2*K23 + K24)/6;
t(i+1) = a + i*h;
end
plot(t, y1)
hold on
plot(t,y2)
end
Answers (2)
darova
on 10 Mar 2019
0 votes
See attached code. Try to write your code as clear and simple as it possible, because it is very easy to make a mistake
Jan
on 10 Mar 2019
ODE integrators work with functions of 1st order only. If you have an equation of 2nd order, you can convert it easily to a system of equations of the 1st order. Instead of calculating y'' you create a system of 2 equations. Then y' is simply the 2nd component of the input, exactly as you have written already:
let x1=y, x2=y'
THis is actuallly trivial. If you have a problem to see it, stop working and drink a cup of coffee.
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!