Asked by Ibrahem abdelghany ghorab
on 15 Dec 2018

dy = @(x,y).2*x*y;

f = @(x).2*exp(x^2/2);

x0=1;

xn=1.5;

y=1;

h=0.1;

fprintf ('x \t \t y (euler)\t y(analytical) \n') % data table header

fprintf ('%f \t %f\t %f\n' ,x0,y,f(x0));

for x = x0 : h: xn-h

y = y + dy(x,y)*h;

x = x + h ;

fprintf (

'%f \t %f\t %f\n' ,x,y,f(x));

end

Answer by Are Mjaavatten
on 17 Dec 2018

Accepted Answer

There are two problems with your code:

- The analytical solution is incorrect
- You increment x inside the for loop. Don't. The for loop does this automatically.

Here is a corrected version:

a = 0.2;

y0 = 1;

x0 = 1;

xn = 1.5;

h = 0.1;

dy = @(x,y)a*x*y; % dy/dx

f = @(x) y0*exp(a/2*(x.^2-1)); % Correct analytic solution

y = y0;

fprintf ('x \t \t y (euler)\t y(analytical) \n') % data table header

fprintf ('%f \t %f\t %f\n' ,x0,y,f(x0));

for x = x0+h : h: xn

y = y + dy(x,y)*h;

fprintf ('%f \t %f\t %f\n' ,x,y,f(x));

end

Choose a smaller step length h to for better accuracy. Alternatively try a higher order method like Runge-Kutta.

Ibrahem abdelghany ghorab
on 17 Dec 2018

modified orImprovedEuler method

and i what 4Runge-kutta for this function dy = @(x,y).2*x*y;

Sign in to comment.

Answer by James Tursa
on 17 Dec 2018

Edited by James Tursa
on 17 Dec 2018

The "Modified" Euler's Method is usually referring to the 2nd order scheme where you average the current and next step derivative in order to predict the next point. E.g.,

dy1 = dy(x,y); % derivative at this time point

dy2 = dy(x+h,y+h*dy1); % derivative at next time point from the normal Euler prediction

y = y + h * (dy1 + dy2) / 2; % average the two derivatives for the Modified Euler step

See this link:

Ibrahem abdelghany ghorab
on 18 Dec 2018

can you write the all code please

James Tursa
on 18 Dec 2018

Not sure what you are asking. The loop is simply

for x = x0 : h: xn-h

dy1 = dy(x,y); % derivative at this time point

dy2 = dy(x+h,y+h*dy1); % derivative at next time point from the normal Euler prediction

y = y + h * (dy1 + dy2) / 2; % average the two derivatives for the Modified Euler step

fprintf ('%f \t %f\t %f\n' ,x+h,y,f(x+h));

end

Note that inside the fprintf I have used x+h, since that is the x value associated with the newly calculated y value.

Ibrahem abdelghany ghorab
on 18 Dec 2018

thank you very much

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## FastCar (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/435910-how-can-i-get-an-improved-euler-s-method-code-for-this-function#comment_651078

## Ibrahem abdelghany ghorab (view profile)

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/435910-how-can-i-get-an-improved-euler-s-method-code-for-this-function#comment_651690

Sign in to comment.