While loop data saved into a vector

3 visualizaciones (últimos 30 días)
turtlish
turtlish el 3 de Dic. de 2015
Comentada: Ilham Hardy el 3 de Dic. de 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!

Respuestas (3)

Ilham Hardy
Ilham Hardy el 3 de Dic. de 2015
counter = 0;
is the problem..
  1 comentario
Ilham Hardy
Ilham Hardy el 3 de Dic. de 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;

Iniciar sesión para comentar.


Adam
Adam el 3 de Dic. de 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.

turtlish
turtlish el 3 de Dic. de 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;

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by