Display data in a while loop as a table
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
ScottB
2025-5-16
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.
采纳的回答
Steven Lord
2025-5-16
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 个评论
更多回答(1 个)
Torsten
2025-5-16
编辑:Torsten
2025-5-16
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!