HELP ! I HAVE WRONG COMMAND WINDOW - RUNGE KUTTA METHOD

2 views (last 30 days)
Hello,
I write a code that use third-order Runge Kutta method. I want my result in tabulated form which i starting with 0, ti, yi (represents numerically estimated value), yei(true value) and et ( true percent absolute relative error).
Finally, I want to plot the true solution together with the numerical solution in the same place.
I have dy/dt = t*e^(3*t)-2*y , step size 0.1 , the true solution ye(t) = 1/5*t*e^(3*t)-(1/25)*e^(3*t)+(1/25)*e^(-2*t)
I write a code but when I run that, I get wrong output. If you run the code you can see that my code doesnt print my i values and other values seperated wrongly.
Here is my code:
clc
clear all
close all
fprintf('%15s %15s %15s %15s %15s\n','i','ti','yi','yei','|Et|')
h=0.1; %initial step size
t=0:h:1; %time array with initial step size
c=length(t); %number of time values with 0.1 step size
y=zeros(1,c); %creating an empty array for numerically calculated 'y' values
%y(0)=0 in this definition. so, initial value is already included.
y_2=zeros(1,c); %creating an empty array for numerically calculated 'y' values
y_true=zeros(1,c); %creating an empty array for exact 'y' values
E=zeros(1,c); %creating an empty array for estimating local truncation errors
%defining the ODE, f = dy/dt
f = @(t,y) t*exp(3*t) - 2*y;
%% Part a
klmn=zeros(1,c-1);
for i=1:1:(c-1)
%defining k1,k2 and k3 for each case
k1(i)=f(t(i),y(i));
k2(i)=f((t(i)+h/2),(y(i)+h/2*k1(i)));
k3(i)=f((t(i)+h),(y(i)-h*k1(i)+ 2*h*k2(i)));
%defining next value of dy/dt, y(i+1) numerically
y(i+1)=y(i)+(h/6)*(k1(i)+4*k2(i)+k3(i));
%real value of y(i+1)
y_true(i+1)=1/5*t(i+1)*exp(3*t(i+1))-(1/25)*exp(3*t(i+1))+(1/25)*exp(-2*t(i+1));
%true error calculation
et(i+1)=abs(y(i+1)-y_true(i+1))./y_true(i+1);
fprintf('%15s %15s %15s %15s %15s\n',i,t(i),y(i),y_true(i),et(i))
end

Answers (0)

Products


Release

R2015a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!