# While loop data saved into a vector

1 visualizzazione (ultimi 30 giorni)
turtlish il 3 Dic 2015
Commentato: Ilham Hardy il 3 Dic 2015
Hello! I'm trying to solve a sparse linear system A*x=b (A=[],b[],x=[]) and I've got a while loop with all the intermediate steps to find the solution. What I'm trying to do is to save in a vector all the intermediate steps.
if true
% code
end
xnew=x0;
k=0;
counter=0;
xdata=[];
maximum number of iterations 2000
while max(abs(xnew-x))>tol && k <2000,
k=k+1;
x=xnew;
xnew=B*x+c;
xdata(counter)=xnew;
counter=counter+1;
end
display(xdata)
x=xnew;
But I get an error message: "Subscript indices must either be real positive integers or logicals." (About the line that says" xdata(counter)=xnew;
Any ideas?
Thanks in advance!
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Risposte (3)

Ilham Hardy il 3 Dic 2015
counter = 0;
is the problem..
##### 1 CommentoMostra NessunoNascondi Nessuno
Ilham Hardy il 3 Dic 2015
-snip-
.. I get another error -.- In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in jacvec (line 33) xdata(counter)=xnew;
-snip-
Try this
xnew=x0;
k=0;
%counter=0;
xdata=[];
maximum number of iterations 2000
while max(abs(xnew-x))>tol && k <2000,
k=k+1;
x=xnew;
xnew=B*x+c;
%xdata(counter)=xnew;
xdata = [xdata xnew];
%counter=counter+1;
end
display(xdata)
x=xnew;

Accedi per commentare.

Adam il 3 Dic 2015
You initialise counter to 0. 0 is not a real positive integer (or logical). So you should initialise
counter = 1;
and that should be fine. Matlab indexes arrays from 1. I don't know if you are more familiar with languages like C++ where indexing is from 0, but for Matlab this is not the case.
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

turtlish il 3 Dic 2015
Thank you both! I changed it but now I get another error -.- In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in jacvec (line 33) xdata(counter)=xnew;
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Matrix Indexing 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!

Translated by