how can i solve this problem with rk4 method?

1 view (last 30 days)
In this case, m=20, k=20, c=40 and initial x=1, initial v=0, t is 0 to 15. please tell me what's wrong in my code
This is my code when 'c=40' please tell me what's wrong in it
f=@(t,x,v) -0.25*v -x; %dvdt
g=@(t,x,v) v; %dxdt
t0=1;
tl=15;
h=0.1;
n=(tl-t0)/h;
T=t0:h:tl;
X=zeros(1,n+1);
V=zeros(1,n+1);
X(1)=1;
V(1)=0;
for j = 1: n
k1f = f(T(j),X(j),V(j));
k1g = g(T(j),X(j),V(j));
k2f = f(T(j)+h/2,X(j)+k1g*h/2,V(j)+k1f*h/2);
k2g = g(T(j)+h/2,X(j)+k1g*h/2,V(j)+k1f*h/2);
k3f = f(T(j)+h/2,X(j)+k2g*h/2,V(j)+k2f*h/2);
k3g = g(T(j)+h/2,X(j)+k2g*h/2,V(j)+k2f*h/2);
k4f = f(T(j)+h,X(j)+k3g*h,V(j)+k3f*h);
k4g = g(T(j)+h,X(j)+k3g*h,V(j)+k3f*h);
X(j+1)= X(j) + (k1g + 2*k2g + 2*k3g + k4g)/6;
V(j+1)= V(j) + (k1f + 2*k2f + 2*k3f + k4f)/6;
end
plot(T,V)

Accepted Answer

Alan Stevens
Alan Stevens on 16 Jun 2021
If m=20, k=20, c=40 then function f should be f = -(c/m)*v - k/m
f=@(t,x,v) -2*v -x; %dvdt

More Answers (0)

Community Treasure Hunt

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

Start Hunting!