Let us suppose to implement the method with constant time step, say dt>0
.
If we wanna integrate the equation up to a time T>0
, we consider a time discretization
tt = 0:dt:T;
We'd better pre-allocate our solution vector for speed purpose, i.e.
yy=zeros(1,length(tt));
yy
will contain the first order-in-time approximation of the solution we will produce (i.e., with little abuse of notation,
yy(1)==y_r(t=0)
and
yy(end)==y_r(t=T) + global error,
where the function y_r=y_r(t)
is our real solution).
Supposedly, we have a first order ODE in normal form, i.e.
dy_r / dt = f(y_r;t)
and an initial datum
y_r(t=0)=y_0
(i.e. we have a Cauchy problem). Thus, we should firstly initialize our solution vector
yy(1) = y_0;
then, we can find the solution for future times, i.e.
N = length(tt);
for t = 2 : N // we should look at future times, thus we start from 2
// NOTE: this is first order explicit Euler scheme.
yy(t) = yy(t-1) + dt*f(yy(t-1),t);
end
We're done. We can now plot the solution.
plot(tt,yy);
Now the point is: are you satisfied with first-order-in-time accuracy?
Think that if you use this scheme to solve e.g. Hamiltonian problems (say the simple harmonic oscillator), it will give artificial excitation to your system (properly, you can see a drift out of your correct Hamiltonian orbit). In few words, after little time your solution is completely artificial.
Indeed, when you solve real problems, you have to carefully consider your problem and your physics, and then choose a proper numerical scheme to solve your equation. Soon, probably you will be asked to implement more accurate schemes such as Runge Kutta (which you can better trust, but just a little bit, at least in their original form).