Display data in a while loop as a table

5 Ansichten (letzte 30 Tage)
rezheen
rezheen am 16 Mai 2025
Bearbeitet: Torsten am 16 Mai 2025
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 Kommentar
ScottB
ScottB am 16 Mai 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Steven Lord
Steven Lord am 16 Mai 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

Weitere Antworten (1)

Torsten
Torsten am 16 Mai 2025
Bearbeitet: Torsten am 16 Mai 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by