Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

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

1 visualizzazione (ultimi 30 giorni)
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 Commento
J. Alex Lee
J. Alex Lee il 8 Set 2020
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)

Risposte (1)

Ayush Gupta
Ayush Gupta il 11 Set 2020
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

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by