Clear Filters
Clear Filters

Creating a Table for Newton's Method

7 views (last 30 days)
I am trying to creat a table for different values that Newton's method approximates for different starting values. I have the following for the method.
x0 = 0.0:0.1:8;
for j = 1:numel(x0)
f = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
fp = @(x) 4*(-exp(-2*x) + sin(2*x) + cos(x));
x(1) = x0(j);
N = 50;
tol = 1e-6;
n = 2;
nfinal = N + 1;
while (n <= N + 1)
fe = f(x(n - 1));
fpe = fp(x(n - 1));
x(n) = x(n - 1) - fe/fpe;
if (abs(fe) <= tol)
nfinal = n;
break;
end
n = n + 1;
end
end
I think I need to add something in the for loop to save the values, but how do I make a table out of this? I would like one collumn to be all the x(0) values and another collumn to be all the values that each x(0) converges to.

Accepted Answer

Walter Roberson
Walter Roberson on 2 Oct 2021
The NaN is because you have a 0 divided by 0
x0 = (0.0:0.1:8).';
results = table(x0);
results.x_final = nan(size(x0));
for j = 1:numel(x0)
f = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
fp = @(x) 4*(-exp(-2*x) + sin(2*x) + cos(x));
x(1) = x0(j);
N = 50;
tol = 1e-6;
n = 2;
nfinal = N + 1;
while (n <= N + 1)
fe = f(x(n - 1));
fpe = fp(x(n - 1));
x(n) = x(n - 1) - fe/fpe;
if (abs(fe) <= tol)
nfinal = n;
break;
end
n = n + 1;
end
results.x_final(j) = x(nfinal);
end
results
results = 81×2 table
x0 x_final ___ ___________ 0 NaN 0.1 9.3521e-05 0.2 8.9191e-05 0.3 0.00012689 0.4 0.00015928 0.5 9.2778e-05 0.6 0.00010227 0.7 0.00010719 0.8 0.00010587 0.9 9.5182e-05 1 0.00013702 1.1 0.00017184 1.2 -0.00011787 1.3 -0.00011629 1.4 -9.1689e-05 1.5 -0.00016472

More Answers (0)

Categories

Find more on Programming 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!