My Newton's Method "for loop" and table only displays the last iteration. I would like it to display all iterations. How do I do this?

2 views (last 30 days)
Here is my code:
%Convergance Criteria
Enr = 1e-8;
%Max iteration
imax = 100;
%Initial Guesses
t0 = 2.2;
t1 = 2.3;
t2 = 2.4;
for i = 1:imax
t = t0;
f = (2*sin(t^2))-(3*t*sin(t^2))+((t^2)*sin(t^2));
df = (4*t*cos(t^2))-(3*sin(t^2))-(6*(t^2)*cos(t^2))+(2*t*sin(t^2))+(2*(t^3)*cos(t^2));
dt = - f/df;
t0 = t + dt;
T = table(i,t,f,dt,t0);
if abs(dt/t) < Enr
break
end
end
  1 Comment
Tristan Blake
Tristan Blake on 6 Feb 2018
%Convergance Criteria
Enr = 1e-8;
%Max iteration
imax = 100;
%Initial Guesses
t0 = 2.2;
t1 = 2.3;
t2 = 2.4;
for i = 1:imax
t = t0;
f = (2*sin(t^2))-(3*t*sin(t^2))+((t^2)*sin(t^2));
df = (4*t*cos(t^2))-(3*sin(t^2))-(6*(t^2)*cos(t^2))+(2*t*sin(t^2))+(2*(t^3)*cos(t^2));
dt = - f/df;
t0 = t + dt;
T = table(i,t,f,dt,t0);
if abs(dt/t) < Enr
break
end
end

Sign in to comment.

Answers (1)

per isakson
per isakson on 6 Feb 2018
Edited: per isakson on 6 Feb 2018
Currently you overwrite the table, T, in every iteration. Replace
T = table(i,t,f,dt,t0);
by
if i == 1
T = table(i,t,f,dt,t0);
else
T(end+1,:) = { i, t, f, dt, t0 }; %#ok<AGROW>
end
test result
T =
i t f dt t0
_ ______ ___________ ___________ ______
1 2.2 -0.23805 -0.1898 2.0102
2 2.0102 -0.0080692 -0.0097849 2.0004
3 2.0004 -0.00031676 -0.00041699 2
4 2 -5.8582e-07 -7.7407e-07 2
5 2 -2.0197e-12 -2.6688e-12 2
>>

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!