2nd order lineair non-homogenous differential equation with EULER not working properly

1 view (last 30 days)
Hi,
I'm trying to solve n'' + 2n' + 3n = e^t + cos(5t) with EULER to get the same results as GeoGebra CAS has, but it's not showing the same graphs. Also the Matlab doesn't go beyond t=2 although I set it to stop at tf=5.
Can someone see what's wrong?
Thank you a lot!
Matlab:
% n''+2n'+3n=0, n(0)=0, n'(0)=2
%Defining functions
first=@(n,x,t) x;
second=@(n,x,t) exp(t) + cos(5*t) - 3*n - 2*x;
%step size
T=.000001;
%max t value
tf=5; %doesn't plot beyond tf=2
%Initial conditions
t(1)=-3;
n(1)=0; %n(0)=0
n2(1)=2; %n'(0)=2
%euler approximation
for i=1:(tf/T)
t(i+1)=t(i)+T;
n(i+1)=n(i)+T*first(n(i),n2(i),t(i));
n2(i+1)=n2(i)+T*second(n(i),n2(i),t(i));
end
plot(t,n)
GeoGebra CAS:

Answers (1)

Torsten
Torsten on 18 Jan 2023
The number of steps to take to reach tend is (tend-tstart)/dT, not tend/dT.
Further, you apply the initial conditions at t = -3, not t = 0.
  5 Comments
Manon
Manon on 19 Jan 2023
thank you a lot Torsten! I've been at it all day yesterday and couldn't get anywhere.
It's weird because I worked the problem out on paper as well and now Matlab gives another awnser to the equations as GeoGebra CAS does...
I worked out C1 and C2 with the given conditions and that gives me the awnser below.
Weird... :(
Torsten
Torsten on 19 Jan 2023
Edited: Torsten on 19 Jan 2023
I also plotted the "solution" from GeoGebra CAS and there are great differences compared to your Euler solution, especially for x < 0. As you can see, MATLAB solution and Euler solution are almost identical.
My guess is that you incorrectly incorporated the two initial conditions for n and n' at x=0.
But it's no problem: if you insert the two "solutions" into the differential equation, you can easily see which of them is correct.

Sign in to comment.

Categories

Find more on Programming 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!