Calculate the error for many time steps in the same file ( Only work for one time step )
Show older comments
I want to calculate the error for my data at different time step (dt) in one file. If I tried one time step, dt, then it works. However, it does not work for many time steps at once. For example, if I have dt=0.0001:0.0001:0.0001, it will give me the right answer. However, if I use dt=0.0001:0.0001:0.0002, then the first data for dt=0.0001 is correct, but the data for dt=0.0002 is incorrect.
% Solve dx/dt=H(x)+1
% H(x)=0 when 0<=x<=0.1
% H(x) = 1, when x>0.1
% Time step
First file
function x=heaviside(x,xo)
if x<xo
x=1;
else x>xo
x=2;
end
end
Second file
j=0;
xin=0; % Initial position at t=0
xo=0.1;
x=xin;
for dt=0.0001:0.0001:0.0002
j=j+1;
tf=0.2; % final time
t=[0:dt:tf];
n=length(t);
for i=1:n-1
% RK4 method
k1=heaviside(x,xo);
k2=heaviside(x+(0.5*dt*k1)',xo);
k3=heaviside(x+(0.5*dt*k2)',xo);
k4=heaviside(x+(dt*k3)',xo);
x(i+1,:) = x(i,:) + ((k1+2*k2+2*k3+k4)/6)'*dt;
end
end
Error(j)=abs(((x(n,:)-0)-(0.3))/0.3); % Calculate the error
clear n j dt t x xo
where, x(n,:) is the final point of x vector, 0 is initial, 0.3 is exact solution. Please helps. Thanks
Accepted Answer
More Answers (0)
Categories
Find more on Numerical Integration and Differential Equations 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!