# how do i put iteration values into a vector?

13 visualizzazioni (ultimi 30 giorni)
Robert il 7 Dic 2013
Commentato: Robert il 7 Dic 2013
Hi, im creating a matlab function that uses the secant method to create an approximation, im trying to take the values that are calculated in my while loop and put them into one vector showing all the values computed at each iteration, i can get my final iterated value to be the first element in the vector but cant get the values calculated before to appear my while loop looks like this
xold=x0;
xa=x1-(f(x1)*(x1-xold))/(f(x1)-f(xold));
iter=0;
while abs(xa-xold)>=D;
iter=iter+1;
xnew=xa-(f(xa)*(xa-xold))/(f(xa)-f(xold));
xold=xa;
xa=xnew;
end
in this x0 and x1 are initial values, iter is the number of iterations and D is the tolerance level of the funtion
also where abouts in this function do i need to put the vector code to show the iterations?
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Wayne King il 7 Dic 2013
Modificato: Wayne King il 7 Dic 2013
I'm not sure from your post, which values you want to retain over the life of the while loop, I'm assuming xnew
I would set the iter to 1 because you can't index a vector from zero in MATLAB and then increment the iter loop counter at the end of the while loop.
Without knowing all your variables, I can't test this, but does the following work?
xold=x0;
xa=x1-(f(x1)*(x1-xold))/(f(x1)-f(xold));
iter=1;
X = [];
while abs(xa-xold)>=D;
X(iter) =xa-(f(xa)*(xa-xold))/(f(xa)-f(xold));
xold=xa;
xa=xnew;
iter=iter+1;
end
##### 3 CommentiMostra 2 commenti meno recentiNascondi 2 commenti meno recenti
Robert il 7 Dic 2013
Done it, thanks so much!!!!!!

Accedi per commentare.

### Più risposte (1)

sixwwwwww il 7 Dic 2013
Modificato: sixwwwwww il 7 Dic 2013
X = 0;
xold=x0;
xa=x1-(f(x1)*(x1-xold))/(f(x1)-f(xold));
iter=0;
X(iter + 1) = xa;
while abs(xa-xold)>=D;
iter=iter+1;
xnew=xa-(f(xa)*(xa-xold))/(f(xa)-f(xold));
xold=xa;
xa=xnew;
X(iter + 1) = xa;
end
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!