Tabulate data from loop iterations
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.
Jonathan Lowe
on 23 Jan 2019
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
Jonathan Lowe
on 23 Jan 2019
Walter Roberson
on 23 Jan 2019
You cannot stop a loop by table headers.
The fprintf() statement I gave showed how to create table headers for display output.
To stop a loop when delta_x exceeds -0.0001 then
while delta_x < -0.0001
Are you sure you do not want to stop when abs(delta_x) becomes less than 0.0001 ?
Jonathan Lowe
on 23 Jan 2019
Walter Roberson
on 23 Jan 2019
while true
....
calculate delta_x
if delta_x satisfies some condition
break
end
end
Categories
Find more on Dates and Time 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!