# Matlab code help on Euler's Method

5,913 views (last 30 days)
Sanjida Ahmed on 11 Apr 2016
Answered: Rakshana on 13 Nov 2022 at 1:54
I have to implement for academic purpose a Matlab code on Euler's method(y(i+1) = y(i) + h * f(x(i),y(i))) which has a condition for stopping iteration will be based on given number of x. I am new in Matlab but I have to submit the code so soon. I am facing lots of error in implementing that though I haven't so many knowledge on Matlab. If anyone provide me so easy and simple code on that then it'll be very helpful for me. Thank you.

James Tursa on 11 Apr 2016
Here is a general outline for Euler's Method:
% Euler's Method
% Initial conditions and setup
h = (enter your step size here); % step size
x = (enter the starting value of x here):h:(enter the ending value of x here); % the range of x
y = zeros(size(x)); % allocate the result y
y(1) = (enter the starting value of y here); % the initial y value
n = numel(y); % the number of y values
% The loop to solve the DE
for i=1:n-1
f = the expression for y' in your DE
y(i+1) = y(i) + h * f;
end
You need to fill in the values indicated, and also write the code for the f line. What is the DE you are trying to solve?
##### 2 CommentsShowHide 1 older comment
James Tursa on 13 Apr 2016
Edited: James Tursa on 13 Apr 2016
After you enter this in the editor and save it, you need to run it either by typing the file name at the command prompt, or by pressing the green triangle Run button at the top of the editor. Since all of the lines end with a semi-colon ;, there will be no output to the screen when this runs. However, the variables are there. If you look in the Workspace list you will see them, or if you issue the whos command you also will see them. To see the result you could plot them. E.g.,
plot(x,y); grid on

h=0.5;
x=0:h:4;
y=zeros(size(x));
y(1)=1;
n=numel(y);
for i = 1:n-1
dydx= -2*x(i).^3 +12*x(i).^2 -20*x(i)+8.5 ;
y(i+1) = y(i)+dydx*h ;
fprintf('="Y"\n\t %0.01f',y(i));
end
%%fprintf('="Y"\n\t %0.01f',y);
plot(x,y);
grid on;
James Tursa on 3 Mar 2021
Edited: James Tursa on 3 Mar 2021
@shireesha myadari Please delete this comment and open up a new question for this.

Bakary Badjie on 14 Jun 2021
what is the Matlab function that implements Euler’s method
##### 2 CommentsShowHide 1 older comment
Israel Morris on 1 Aug 2022
Have you always been interested in the online converter? here, because it is always helpful for you to convert large size into a small size and vice versa. Thus, you might be very lucky too who solves most of your problems all at once by using the online converter, which is able to help you with everything other than figure and picture editing.

Rakshana on 13 Nov 2022 at 1:53
if true
% code
end

Rakshana on 13 Nov 2022 at 1:54
h=0.5; x=0:h:4; y=zeros(size(x)); y(1)=1; n=numel(y); for i = 1:n-1 dydx= -2*x(i).^3 +12*x(i).^2 -20*x(i)+8.5 ; y(i+1) = y(i)+dydx*h ; fprintf('="Y"\n\t %0.01f',y(i)); end %%fprintf('="Y"\n\t %0.01f',y); plot(x,y); grid on;