Creating a Table for Newton's Method
조회 수: 2 (최근 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.
댓글 수: 0
채택된 답변
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
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!