Using Euler method to solve second order ODE
Show older comments
Hello,
I'm trying to write a program that usese Euler method to solve second order ODE. (represnts the movment of a package hanging from the roof with a spring).
I eventually will need to solve a more complex one, but as long as the simple one doesn't work, I have no reason to continue.
My ODE is: y'' = -25*y + 440.19 ;
For a reason I don't understand, my plot is not converging with the calculated solution for the ODE.
The code and the plot I'm getting are in the pictures. (the expected result was done with Runge-Kutta but since I can't manege to use it so solve a second order ODE I'm trying to understand the Euler method).
Zp_dotaim = y'' ; Zp_dot = y' ; Zp = y
Initial values : y'(0) = 0 ; y(0) = 18 ;
Thank you!
Zp_dot = zeros(1,1000) ; % prealocating vectors [m/sec]
Zp = zeros(1,1000) ; % prealocating vectors [m]
Zp(1) = 18 ; % initial condition
t = linspace(1,100,1000) ; % creating time vector [sec]
h = 0.01 ; % time step
for i = 1:999
% Zp_dotaim =@(Zp) 25*((2/(20-Zp))-1)*(Zp-20)-9.81 ;
Zp_dotaim =@(Zp) -25*Zp + 440.19 ;
Zp_dot(i+1) = Zp_dot(i) + h*Zp_dotaim(Zp(i)) ;
Zp(i+1) = Zp(i) + h*Zp_dot(i) ;
end
exact = (0.3924*cos(5*t)+17.6076);
plot(t,Zp,'r',t,exact,'b--') ; title('Zp(t)') ; grid on ;
xlabel('t [sec]') ; ylabel('Zp(t) [m]') ;

Accepted Answer
More Answers (1)
Tom Brenner
on 19 Jul 2022
1 vote
You can't solve a second order differential equation with a single initial condition. You must have two. In this case, you assume that the first value of Zp_dot is zero (the vector was initialized with zeros) and add to this zero the approximate value of h times the second derivative.
You should determine how the exact solution 0.3924*cos(5*t)+17.6076 was arrived at (i.e., what the two initial conditions should be), and then correct your code.
1 Comment
Yuval Levy
on 19 Jul 2022
Edited: Yuval Levy
on 19 Jul 2022
Categories
Find more on Numeric Solvers in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

