Help storing my iterations into my variables

2 ビュー (過去 30 日間)
daniel choudhry
daniel choudhry 2020 年 11 月 2 日
回答済み: VBBV 2020 年 11 月 2 日
I am having trouble storying my iterations into my variables X,EE, F that are inside my while loop
%Function and derivatives
function [X,EE,F]=my_newton(x0)
f = @ (x) x^2; %function
fp = @ (x) 2*x; % Derivative
X=[];
EE=[];
F=[];
%%%% Newton's Method search theory (c) part (b)%%%%
x0 = .5; % Starting location
y0 = f(x0);
es = 10^(-4); % Want error less than 0.5%
ea = 1.0; % Initialize approx. error
k = 0;
xr = x0; % initialize root guess
yr = y0;
yrp = fp(xr);
while (ea > es) && (k <= 2)
k = k +1;
xr_old = xr; % Updating previous root location
yr_old = yr; % function evaluation
yrp_old = yrp; % and derivative evaluation at xr_old
xr = xr_old - yr_old/yrp_old; % new root location guess
yr = f(xr); % Calculating function eval at new guess
yrp = fp(xr); % Calc. derivative eval at new guess
ea = abs((xr - xr_old)/xr); % updating relative approx. error
X=[xr]
EE=[ea];
F=[yrp];
if k>20
disp('To many iterations')
return
end
end
fprintf('Approximate root after %d operations is: %12.15f with approximate error %12.15f',k,xr,ea);
end

採用された回答

VBBV
VBBV 2020 年 11 月 2 日
Inside the while loop use
%if true
% code
% end
X(k) = xr;
EE(k) = ea;
F(k) = yrp;

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by