Creating a Table for Newton's Method

3 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2021-10-2
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Interpolation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by