How to find error in Runge Kutta 4th Order
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
function RungeKutta4=RK4 (f,a,b,n,t0,y0)
h=(b-a)/n;
%n=(b-a)/h;
t=a:h:b;
k1=zeros(1,n+1);
k2=k1;
k3=k2;
k4=k3;
y=k4;
y(1,1)=y0;
RK4Y=k4;
for i=1:length(t)
k1(1,i)=h*feval('f',t(i),y(i));
k2(1,i)=h*feval('f',t(i)+h/2,y(i)+k1(i)/2);
k3(1,i)=h*feval('f',t(i)+h/2,y(i)+k2(i)/2);
k4(1,i)=h*feval('f',t(i)+h,y(i)+k3(i));
RK4Y(1,i)=y(i)+1/6*(k1(i)+2*k2(i)+2*k3(i)+k4(i));%y1
y(1,i+1)=RK4Y(i);
end
RK4Y
RungeKutta4Y=RK4Y(n)
plot(t,RK4Y,'ro');hold on;
g=350*(1-exp((-0.2*t)/(7-5*exp(-0.2*t))));
plot(t,g);hold off;
end
Respuestas (1)
Jan
el 28 de Mayo de 2021
Editada: Jan
el 28 de Mayo de 2021
You did not mention, which problems occur. So before the problem can be solved, the readers have to guess, what the problem is.
You do not want to evaluate the character 'f', but the function handle stored in the variable f :
% Replace:
feval('f', ...
% by
feval(f, ...
There is no need to store the intermediate values of k1 to k4.
Collecting the trajectory in the variable y is enough. There is no need to store in in RK4Y again.
Storing the result in y(i+1) creates a final value at y(length(t) + 1). So y is longer than t. Solution: Run the loop until length(t)-1.
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!