MATLAB: Euler’s method help

eulerhomeworkplot

I am trying to plot an euler's method for dx/dt=-100x for x(t)=x(0)e^(-100t) with x(0)=1.My code is
x = 1;
h = 0.001;
n_final = 5;
n = 0;
while (n < n_final)
x(n+h) = x(n)+h*(-100*x(n));
n = n+h;
end
plot(x(n), n)
why is my code not working? I want to plot the numerical solution xn vs x.

Best Answer

Since your ODE is in terms of t, I would suggest you use t in your code to make it more readable to you. Go ahead and keep n but use it only for the indexing. Modifying your code (CAUTION untested):
t_final = 5; % final time
h = 0.001; % step size
% pre-allocate t vector here
% pre-allocate x vector here
t(1) = 0; % initial t
x(1) = 1; % initial x
n = 1; % start the indexing at 1
while (t(n) < t_final)
x(n+1) = x(n) + h*(-100*x(n)); % the next x
t(n+1) = t(n) + h; % the next t
n = n + 1; % the next index
end
plot(t, x) % plotting t and x
I will leave it to you to figure out how to pre-allocate the t and x vectors. How many points will there be between 0 and t_final given a step size of h?
Related Question