Display data in a while loop as a table
조회 수: 3 (최근 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!