While loop data saved into a vector

1 回表示 (過去 30 日間)
turtlish
turtlish 2015 年 12 月 3 日
コメント済み: Ilham Hardy 2015 年 12 月 3 日
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!

回答 (3 件)

Ilham Hardy
Ilham Hardy 2015 年 12 月 3 日
counter = 0;
is the problem..
  1 件のコメント
Ilham Hardy
Ilham Hardy 2015 年 12 月 3 日
-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;

サインインしてコメントする。


Adam
Adam 2015 年 12 月 3 日
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 2015 年 12 月 3 日
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;

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by