Info

この質問は閉じられています。 編集または回答するには再度開いてください。

I am trying to store the values of each iteration of 0.01 in my for loop into a matrix. Could anyone help?

1 回表示 (過去 30 日間)
MegAnne Anast
MegAnne Anast 2020 年 9 月 8 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
function [r k] = root_finder(f,x0,kmax,tol)
x1 = x0; %initial x1
%for loop for x1 from 2 to kmax as intial value x1 is given
for i = 2 : kmax
%evaluating function f @x1 and comparing with tolerance given
if tol > abs(feval(f,x1))
r = x1; % if |f(xk)| < tol then we have to stop
k = i;
break;
else
x1 = x1 + 0.01; %incrementing x1 with 0.01
end
end
end %function ends
  1 件のコメント
J. Alex Lee
J. Alex Lee 2020 年 9 月 8 日
You want to save the history of x1? It would only make sense if you wanted to also save the histories of the function value f (which you are trying to zero).
Typically, you would use "r" to denote the residual, or function value, so
function [rList,xList,k] = root_finder(f,x1,kmax,tol)
for k = 1 : kmax
xList(i) = x1;
% evaluating function f @x1 and comparing with tolerance given
rList(i) = feval(f,x1);
if tol > abs(r(i))
break;
end
x1 = x1 + 0.01; %incrementing x1 with 0.01
end
end %function ends
Note that this is an objectively bad root-finding algorithm.
Also note that if your function f accepts vector x, then you could also do
xList = (x0:0.01:xEnd)
rList = f(xList)
[rBest,idxBest] = min(abs(rList))
xBest = xList(idxBest)

回答 (1 件)

Ayush Gupta
Ayush Gupta 2020 年 9 月 11 日
The history of tolerance and corresponding x values can be stored if we treat them as vectors and in each iteration of for loop the value at that point is stored. Refer to the following code to see how it works:
function [r, k] = root_finder(f,x0,kmax,tol)
x1 = x0; %initial x1
%for loop for x1 from 2 to kmax as intial value x1 is given
for i = 2 : kmax
%evaluating function f @x1 and comparing with tolerance given
r(i) = abs(feval(f,x1));
k(i) = x1;
% if |f(xk)| < tol then we have to stop
if tol >r(i)
break;
end
x1 = x1 + 0.01; %incrementing x1 with 0.01
end
end %function ends

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by