What's wrong with this code?

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

 采纳的回答

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')

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by