You are on page 1of 9

RK2

clear all;
A = [0 1 ; 0.2*(y(1))^2-1 0];
n=32/101;
time_period = 0:n:32;
initial = [1 0];
[t,y] = ode45(@myode45function, time_period, initial);
qstar = zeros(2,length(t));
% Preallocate array
qstar(:,1) = initial;
solution at t=0.
for i=1:(length(t)-1)
k1 = A*qstar(:,i);
deriv
q1 = qstar(:,i)+k1*(n/2);
k2 = A*q1;
value.
qstar(:,i+1) = qstar(:,i) + k2*n;
q
end
plot(t,y(:,1),t,qstar(1,:));
legend('Exact','Approximate');

% Initial condition gives


% Approx for y gives approx for
% Intermediate value
% Approx deriv at intermediate
% Approx solution at next value of
% qstar = first row of qstar

4000
Exact
Approximate

2000

-2000

-4000

-6000

-8000

10

15

20

25

30

35

1
Exact
Approximate

0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1

10

15

20

25

30

35

1.5
Exact
Approximate

0.5

-0.5

-1

-1.5

10

15

20

25

30

35

1
Exact
Approximate

0.5

-0.5

10

15

20

25

30

35

1.5
Exact
Approximate

0.5

-0.5

-1

-1.5

10

15

20

25

30

35

1
Exact
Approximate

0.5

-0.5

10

15

20

25

30

35

Adams-Bashworth
clear all
clc
% Solve y''(t)+py'(t)+w^2(t)=0, y'(0)=0, y(0)=1
q0 = [1; 0];
% Initial Condition
w=1;
p=0.5;
n=32/101;
% Time step
t = 0:n:32;
% t goes from 0 to 32 seconds.
A = [0 1 ; -w^2 -p];
% A Matrix
c1=0;
c2=1;
yexact = c1*sin(t)+c2*cos(t);
%Exact solution
qstar = zeros(2,length(t));
% Preallocate array
%Runge-Kutta 2nd Order to approximate i=2
qstar(:,1) = q0;
% Initial condition gives solution
at t=0.
k1 = A*qstar(:,1);
% Approx for y gives approx for
deriv
q1 = qstar(:,1)+k1*(n/2);
% Intermediate value
k2 = A*q1;
% Approx deriv at intermediate
value.
qstar(:,2) = qstar(:,1) + k2*n;
% Approx solution at next value of
q
%Adam-Bashforth 2nd Order
for i=2:(length(t)-1)
qstar(:,i+1) = qstar(:,i) + (1.5*qstar(:,i)-0.5*qstar(:,i-1))*n;
end
plot(t,yexact,t,qstar(1,:));
% qstar = first row of qstar
legend('Exact','Approximate');

20

#10

12

Exact
Approximate

18
16
14
12
10
8
6
4
2
0

10

15

20

25

30

35

You might also like