Tabulate data from loop iterations
12 views (last 30 days)
Show older comments
I am creating a Newton-Raphson method code to create a table to display the x value and delta x value. This is my code so far. Although it works as is, I would like the loop to only run while delta_x is <= -0.001. Right now I am hard coding the number of iterations. Also, how can I add colum headers to the displayed table?
clc;
clear all;
x = 5;
i = 0;
T = table;
Table = zeros(9, 3);
for i = 1:10
x_new = x;
delta_x = -(x.^4 - 5*x.^3 + 9*x + 3)./(4*x.^3 - 15*x.^2 + 9);
x = x + delta_x;
Table(i, :, :) = [i delta_x x_new];
fprintf('%d %.4f %.4f\n',Table(i, :, :));
i = i + 1;
end
<<
1 -0.3582 5.0000
2 -0.1042 4.6418
3 -0.0086 4.5375
4 -0.0001 4.5290
5 -0.0000 4.5289
6 -0.0000 4.5289
7 -0.0000 4.5289
8 -0.0000 4.5289
9 -0.0000 4.5289
10 -0.0000 4.5289
2 Comments
Stephen23
on 23 Jan 2019
"I would like the loop to only run while delta_x is <= -0.001"
Use a while loop.
Answers (1)
Walter Roberson
on 23 Jan 2019
Do not use %d by itself for this purpose: use %Nd where N is a number. For example %15d .
For the headers you would use things like
fprintf('%3s %15s %15s\n', 'i', 'delta_x', 'x_new')
4 Comments
Walter Roberson
on 23 Jan 2019
while true
....
calculate delta_x
if delta_x satisfies some condition
break
end
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!