Tabulate data from loop iterations

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 个评论

"I would like the loop to only run while delta_x is <= -0.001"
Use a while loop.
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

请先登录,再进行评论。

回答(1 个)

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 个评论

I appreciate the input, however it does not provide input for the question asked about stoping the loop via delta_x and table headers
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 ?
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)
while true
....
calculate delta_x
if delta_x satisfies some condition
break
end
end

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by