Solve IVP with modified Euler's method

19 views (last 30 days)
Kevin Mekulu
Kevin Mekulu on 13 Nov 2017
Answered: My Anh Vu on 1 Apr 2023
I am trying to solve the initial value problem x'(t) = t/(1+x^2) with x(0) = 0 and 0 <= t <= 5 using modified Euler's method with 10 steps however I am not too sure about my code can anyone double check/provide a more efficient code? thanks in advance
function [T,Y] = euler_modified(f,a,b,ya,m)
h = (b - a)/m;
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m,
Y(j+1) = Y(j) + h*feval(f,T(j) + h/2,Y(j) + h*feval(f,T(j),Y(j)));
T(j+1) = a + h*j;
end
  1 Comment
John D'Errico
John D'Errico on 13 Nov 2017
Why do you care if the code is not as efficient as you wish? This is homework, as otherwise, you would not want to use Euler's method in any form. If not homework, then there are batter methods to solve an ODE, and they are already written. NEVER write code when professionally written code is given to you as part of the language itself.

Sign in to comment.

Answers (2)

ali alnashri
ali alnashri on 14 Apr 2021
function [T,Y] = euler_modified(f,a,b,ya,m)
h = (b - a)/m;
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m,
Y(j+1) = Y(j) + h*feval(f,T(j) + h/2,Y(j) + h*feval(f,T(j),Y(j)));
T(j+1) = a + h*j;
end

My Anh Vu
My Anh Vu on 1 Apr 2023
Y(j+1) = Y(j) + h*feval(f,T(j) + h/2,Y(j) + h*feval(f,T(j),Y(j)));
should be Y(j+1) = Y(j) + h*feval(f,T(j) + h/2,Y(j) + h/2*feval(f,T(j),Y(j)));
Good luck!

Community Treasure Hunt

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

Start Hunting!