How do I make a function file that can calculate the modified eulers method?
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!