%% this is a sample .m file to solve a first order d.e. using Euler's method.
%% definitions
y0 = 1; %initial condition
h = 0.01; % time step
t = 0:h:2; % time interval you want. this goes from 0 to 2 seconds
yNumerical = zeros(size(t)); %preallocates array. good practice, optional
%run section to make sure it works; check values of h, y0, t, yNumerical
%% let's calculate our numerical solution yNumerical
yNumerical(1) = y0; %this is the first point. matlab starts at 1, not zero
%run this section to make sure it works
%% this is my "try it out" before doing the for loop.
% dy/dt = -2y + 3e^(-4t)
% calculating yNumerical(2)
yPrime(1) = -2*yNumerical(1) + 3*exp(-4*t(1)); %dy/dt = yt^3 - 1.5y
yNumerical(2) = yNumerical(1)+yPrime(1)*h; %y(i+1) = y(i) + (dy/dt)(i)*h
%run this section to make sure it works
%% now rewrite the above inside a for loop
for i=1:length(t)-1; %repeat for all the times you want
yPrime(i) = -2*yNumerical(i) + 3*exp(-4*t(i));
yNumerical(i+1) = yNumerical(i) + yPrime(i)*h;
end;
%run to make sure this works. check first 3 entries since we calculated
%those values. comment out what we don't need; clear everything; run again
%% plot, save and save
plot(t, yNumerical)
aNameYouFindUseful = yNumerical; %saves the array in another array
save(eulerMethod.mat) %saves the entire workspace