MATLAB: What’s wrong with this code

euler's method

clear all
%%Initialization of Parameters
it = 0;
ft = 2;
h = 0.2;
iy = 0;
%%Derived Variables
numSteps = (ft - it)/h;
soln = zeros(1, numSteps+1);
soln(1) = iy;
timeAxis = [it: h: ft]
%%Anonymous Functions
f=@(y) 1+y^2;
%%For Loop
for i = 2:numSteps+1
soln(i) = soln(i-1) + h*(f(soln(i-1)));
end
%%Plot
figure(1)
plot(timeAxis, soln)
grid on
Every time this is run, the solutions run up exponentially and I know it's not correct. I'm not very familiar with the Euler method and I assume it's because I'm not utilizing it correctly. Any suggestions? I'm desperate

Best Answer

The code runs fine, what problem are you trying to solve?
EDIT
.
. Try this.
clear all
%%Initialization of Parameters
it = 0;
ft = pi/2; % Don't cross singularities.
h = 0.001; % Smaller step is better....
iy = 0;
%%Derived Variables
numSteps = floor((ft - it)/h);
soln = zeros(1, numSteps+1);
soln(1) = iy;
timeAxis = [it: h: ft];
%%Anonymous Functions
f=@(y) 1+y.^2;
%%For Loop
for ii = 2:numSteps+1
soln(ii) = soln(ii-1) + h*(f(soln(ii-1)));
end
%%Plot
figure(1)
plot(timeAxis, soln)
grid on
% Now plot the true solution with the Euler approximation.
hold on
plot(timeAxis,tan(timeAxis),'r')
ylim([0 10])
legend('Euler Solution','True Solution')