Display data in a while loop as a table
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
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.
Akzeptierte Antwort
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);
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
0 Kommentare
Weitere Antworten (1)
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)
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!