MATLAB: Trouble with Euler’s Method in MatLab

euler method

I am supposed to use the Euler method to solve the equation Dy = 2*y + cos(t) with a step size h = 0.5 and n = 12 steps. This should be graphed and further analysis will be based on the graph. However, I think my Euler method is incorrect as my graph doesn't help me out in any way, it just looks like a backwards L with the last value of t having a much larger value of y when compared to every other point on the graph. I have included by code so far. I would appreciate any help, I am not experienced in MatLab at all, so I could use the help.
Here is my Euler method code:
function [t, y] = myeuler(f, tinit, yinit, b, n)
h = (b - tinit)/n;
t = zeros(n + 1, 1);
y = zeros(n + 1, 1);
t(1) = tinit;
y(1) = yinit;
for i = 1:n
t(i + 1) = t(1) + h;
y(i + 1) = y(i) + h*f(t(i), y(i));
end
And this is my other code for finding the graph of the values from solving using the Euler Method.
f = @(t,y) 2*y + cos(t);
[t, y] = myeuler(f,0,-2/5,6,12);
figure(1);
plot(t,y)
This is the graph I get when I plot the function:
%

Best Answer

Replace:
for i = 1:n
t(i + 1) = t(1) + h;
y(i + 1) = y(i) + h*f(t(i), y(i));
end
by
for i = 2:n
% ^ t(1) and y(1) are defined already
t(i + 1) = t(i) + h;
% ^ not 1
y(i + 1) = y(i) + h*f(t(i), y(i));
end
Related Question