Tabulate data from loop iterations

12 views (last 30 days)
Jonathan Lowe
Jonathan Lowe on 22 Jan 2019
Commented: Walter Roberson on 23 Jan 2019
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
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
Jonathan Lowe on 23 Jan 2019
This code gives me the desired output and stops corectly. However, the method I used to generate a table is not working. How can I formulate this into a table?
fprintf('%s %10s %8s\n', 'i', 'delta_x', 'x_new')
x = -5;
i = 0;
T = table;
Table = zeros(9, 3);
delta_x = -(x.^4 - 5*x.^3 + 9*x + 3)./(4*x.^3 - 15*x.^2 + 9);
while abs((delta_x)) >= 0.0001
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

Sign in to comment.

Answers (1)

Walter Roberson
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
Jonathan Lowe on 23 Jan 2019
I apologize, my wording of that was confusing, did not mean to imply I wanted to stop the loop via table headers. Knowing I need to use a while loop, I must predefine delta_x for it to work, however delta_x isnt defined until inside the loop. How can I implement this? (I am fairly new to loop structures)
Walter Roberson
Walter Roberson on 23 Jan 2019
while true
....
calculate delta_x
if delta_x satisfies some condition
break
end
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!