Display data in a while loop as a table

5 views (last 30 days)
Hello, I'm trying to approximate the root of a function using Newton's method and display the results as a table. I've found my results but am having trouble displaying the table appropriately. I have a function file, and a script. This is my code:
Function:
function x = newtonimproved_4_7(f,df,x0,tol)
x=x0; y=f(x); n=0;
while abs(y)>tol
n=n+1;
x=x-y/df(x);
y=f(x);
t=table(n',x',y');
header={'n','x_n','f(x_n)'};
t.Properties.VariableNames=header;
disp(t)
end
Script:
clear, clc
format longg
f=@(x) x^3-5; df=@(x) 3*x^2;
newtonimproved_4_7(f,df,1,0.00001);
Also, if I can decompose all of it into just a script file and perhaps use syms instead, that'd be great, but that's not the main premise of this question.
Thanks.
  1 Comment
ScottB
ScottB on 16 May 2025
I don't have MATLAB in front of me at the moment but it seems that you should define a table before the loop and add entries to it in the loop then display the table after the loop has completed and you have reached the defined tolerance.
I think the current code is repeatedly defining a table with one set of entries, displaying that table then overwriting it in the next interation of the loop.

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 16 May 2025
Rather than building a new table each time, I'd create one before your loop and add to it then display it at the end.
f=@(x) x^3-5; df=@(x) 3*x^2;
newtonimproved_4_7(f,df,1,0.00001);
n x_n f(x_n) _ ______ __________ 1 2.3333 7.7037 2 1.8617 1.4523 3 1.722 0.10624 4 1.7101 0.00073505 5 1.71 3.6014e-08
function x = newtonimproved_4_7(f,df,x0,tol)
x=x0; y=f(x); n=0;
header={'n','x_n','f(x_n)'};
t = table('Size', [0 3], ...
'VariableTypes', ["double", "double", "double"], ...
'VariableNames', header);
while abs(y)>tol
n=n+1;
x=x-y/df(x);
y=f(x);
t(end+1, :) = {n, x, y};
end
disp(t)
end

More Answers (1)

Torsten
Torsten on 16 May 2025
Edited: Torsten on 16 May 2025
clear, clc
format longg
f=@(x) x^3-5; df=@(x) 3*x^2;
[n,X,Y] = newtonimproved_4_7(f,df,1,0.00001);
t=table((1:n).',X',Y');
header={'n','x_n','f(x_n)'};
t.Properties.VariableNames=header;
disp(t)
n x_n f(x_n) _ ________________ ____________________ 1 2.33333333333333 7.7037037037037 2 1.86167800453515 1.45228738979579 3 1.72200188005861 0.106235772741379 4 1.71005973660029 0.000735045685184232 5 1.70997595078219 3.601359477301e-08
function [n,X,Y] = newtonimproved_4_7(f,df,x0,tol)
x=x0; y=f(x); n=0;
X(1) = x; Y(1) = y;
while abs(y)>tol
n=n+1;
x=x-y/df(x);
y=f(x);
X(n) = x;
Y(n) = y;
end
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!