필터 지우기
필터 지우기

How do I make a function file that can calculate the modified eulers method?

조회 수: 2 (최근 30일)
Noah Poole
Noah Poole 2017년 5월 11일
편집: James Tursa 2017년 5월 11일
I have to create a function file that can use the modified eulers method to calculate for any ode. It is supposed to work like the already existing ode45 function that can calculate with inputs odefun, an initial condition, a time span and a step size. I've tried to do this several times and have come up with the code
function [tout,yout] = modified(odefun,tspan,y0,h)
yout(1) = y0; %setting initial y value
tout(1) = tspan(1); %setting initial t value
i=1;
while tout(i) < tspan(2);
i = i + 1;
yout(i+1) = yout(i) + h*odefun(tout(i),yout(i)); %need to calculate eulers method to find modified eulers method
tout(i+1) = tout(i) + h;
for i=1
tout(i+1)=tout(i)+(h); %modified eulers method
odefun(i+1)=odefun(i)+(odefun(i)+odefun(i+1))*(h/2);
end
end
end
however does not work. can anyone suggest a better code? thank you

답변 (1개)

James Tursa
James Tursa 2017년 5월 11일
편집: James Tursa 2017년 5월 11일
For Modified Euler's Method, you simply average the derivative at your initial point and next point, and then use that to take a step. E.g., you already have this:
yout(i+1) = yout(i) + h*odefun(tout(i),yout(i));
tout(i+1) = tout(i) + h;
So now just use that result and pass it to your odefun again, using the average of your two odefun calls to take your Modified Euler step. E.g., just add this line
yout(i+1) = yout(i) + h*(odefun(tout(i),yout(i)) + odefun(tout(i+1),yout(i+1)))/2;
And get rid of that second inner for-loop. The code that calls odefun(i) and odefun(i+1) doesn't even make sense, does it? In your previous code you are supposed to pass a t and a y into odefun, so what do you expect for a result if you simply pass in i and i+1 as you are currently doing? These are not the correct inputs for odefun.
Another thing you need to do is move the i increment code after the yout(i+1) and tout(i+1) code. The way you have it now the yout(i) and tout(i) values are being used before they are being set.

카테고리

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