Ralston's method function

조회 수: 39 (최근 30일)
Emily Gallagher
Emily Gallagher 2019년 12월 7일
댓글: darova 2019년 12월 8일
I am trying to write a function for Ralston's method, a second order Runge Kutta method. My function does not appear to be graphing correctly in another script. Is there something wrong with my function?
function [t, y] = ralston( f, tspan, y0, n)
% ralston implement ralston method
a = tspan(1);
b = tspan(2);
h = (b - a)/n;
t = a + h*(0:n)';
y = 0*t; %vector w all elements zero
y(1) = y0;
for i = 1:n
k1 = h*f(t(i), y(i));
k2 = h*f(t(i) + 3*h/4, y(i) + 3*k1/4);
y(i+1) = y(i) + k1/3 + 2*k2/3;
end
end
  댓글 수: 1
darova
darova 2019년 12월 8일
Can you attach function f?

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

답변 (1개)

Jim Riggs
Jim Riggs 2019년 12월 7일
There is an error in your function in the k2 term. For Ralstons method, it should be:
k1 = h*f(t(i), y(i));
k2 = h*( f( t(i) + 2*h/3, y(i) + 2*k1/3 ) );
  댓글 수: 1
Jim Riggs
Jim Riggs 2019년 12월 7일
편집: Jim Riggs 2019년 12월 7일
After some further review, there is also an error in y(i+1). Ralston's method should be:
k1 = h*f( t(i), y(i) );
k2 = h*f( t(i) + 2*h/3, y(i) + 2*k1/3 );
y(i+1) = y(i) + k1/4 + 3*k2/4;
or
k1 = f( t(i), y(i) );
k2 = f( t(i) + 2*h/3, y(i) + 2*h*k1/3 );
y(i+1) = y(i) + h*(k1/4 + 3*k2/4);
Also note that in order for the function to graph as expected, you must supply the correct starting value, y0.

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

Community Treasure Hunt

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

Start Hunting!

Translated by