Azzera filtri
Azzera filtri

RK4 Errors in MATLAB

2 visualizzazioni (ultimi 30 giorni)
Kyle Broder
Kyle Broder il 4 Ago 2016
Commentato: Torsten il 4 Ago 2016

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.

Risposte (1)

Walter Roberson
Walter Roberson il 4 Ago 2016
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 Commento
Torsten
Torsten il 4 Ago 2016
... and t0 should be greater than 0.
Best wishes
Torsten.

Accedi per commentare.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by