Matt Donovan - Lab 9

ode_methods.m

a=0;
b=2;
z=2;
eflop=[];
r2flop=[];
r4flop=[];

int = [5 21 101];
num = length(int);

for i = int,
        flops(0);
        eul = euler_meth(a,b,i,z);
        x= flops;
        eflop=[eflop x];

        flops(0);
        r2=rk2(a,b,i,z);
        x= flops;
        r2flop = [r2flop x];


        flops(0);
        r4=rk4(a,b,i,z);
        x= flops;
        r4flop = [r4flop x];

        h=(b-a)/(i-1);
        t=a:h:b;
        y=t+2*exp(-2 .*t);

        figure, clf reset, hold on
        plot(t,y);
        plot(t,eul,':');
        plot(t,r2, '--');
        plot(t,r4, '-.');
end

fprintf(1, 'Intervals   Euler Flops   Rk2 Flops   Rk4 Flops\n');

for k =1:num,

fprintf(1,'  %5d   %10d   %10d  %10d\n',int(k)-1,eflop(k),r2flop(k),r4flop(k));

end

figure(1);
title('ODE graph with 5 points');
xlabel(' t');
ylabel(' y(t)');

figure(2);
title('ODE graph with 21 points');
xlabel(' t');
ylabel(' y(t)');

figure(3);
title('ODE graph with 101 points');
xlabel(' t');
ylabel(' y(t)');

euler_meth.m


function[values] = euler_meth(a,b,n,x);
k=0;
values(1)=x;
h = (b-a)/(n-1);
t=a;
for k=2:n,
        x=x+h*func(t,x);
        t=t+h;
        values =[values x];
end

rk2.m


function[values] = rk2(a,b,n,y);
clc;

values(1) = y;
h = (b-a)/(n-1);
t = a;

for k = 2:n,
        f1 = h*func(t,y);
        f2 = h*func((t+h),(y+f1));
        y = y + (f1 +f2)/2;
        t = t + h;
values = [values y];
end

rk4.m

function[values] = rk4(a,b,n,y);
clc;

values(1) = y;
h = (b-a)/(n-1);
t = a;

for k = 2:n,

        f1 = h*func(t,y);
        f2 = h*func((t+h/2),(y+f1/2));
        f3 = h*func((t+h/2),(y+f2/2));
        f4 = h*func((t+h),(y+f3));
        y = y + (f1 +2*f2 + 2*f3 +f4)/6;
        t = t+h;
values = [values y];
end