RK4 Errors in MATLAB

조회 수: 2 (최근 30일)
Kyle Broder
Kyle Broder 2016년 8월 4일
댓글: Torsten 2016년 8월 4일

I'm trying to solve the following ODE using RK4 $$F = \frac{1}{50t^2}$$.

My code is the following

    function [t,y]=euler2(y0,dt,t0,tf)
    t=t0:dt:tf;
    y=zeros(1,length(t));
    y(:,1)=y0;
    F = @(t,r) 1/(50*Power(t,2));
    for i = 1:length(t)-1
    k1 = F(y(:,i),t(i));
    k2 = F(y(:,i)+0.5*dt*k1,t(i)+0.5*dt);
    k3 = F(y(:,i)+0.5*dt*k2,t(i)+0.5*dt);
    k4 = F(y(:,i)+dt*k3,t(i)+dt);
    y(:,i+1) = y(:,i) + dt*(k1+2.0*(k2+k3)+k4)/6.0;
    end
    end

When I run the code however, with y0 = 50 for example, or any other number, this yields just an array of zeros and eventually NaN.

Please help.

답변 (1개)

Walter Roberson
Walter Roberson 2016년 8월 4일
You use
F = @(t,r) 1/(50*Power(t,2));
Power appears to be undefined in the code you gave. Perhaps you are thinking of power
Your F function takes t (presumably time) as the first variable and r (unknown purpose) as its second column, and it ignores the second parameter. But you are invoking
k1 = F(y(:,i),t(i));
in which you appear to be passing y as the first parameter and a time as the second parameter. That k1 y(:,i) is going to be received into the parameter that F knows as t, and that k1 t(i) is going to be received into the parameter that F knows as r (where it is going to be ignored).
For the sake of the readers, you need to be consistent about whether it is your first parameter or the second parameter of F that is the time parameter.
  댓글 수: 1
Torsten
Torsten 2016년 8월 4일
... and t0 should be greater than 0.
Best wishes
Torsten.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by