# While loop data saved into a vector

4 views (last 30 days)
turtlish on 3 Dec 2015
Commented: Ilham Hardy on 3 Dec 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?

Ilham Hardy on 3 Dec 2015
counter = 0;
is the problem..
Ilham Hardy on 3 Dec 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;

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.

turtlish on 3 Dec 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;

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by