Index out of bounds in a for loop

3 ビュー (過去 30 日間)
HIRAKJYOTI BASUMATARY
HIRAKJYOTI BASUMATARY 2017 年 10 月 2 日
コメント済み: Guillaume 2017 年 10 月 3 日
I am trying to loop till the length of Ytotal. But inside the loop some of the elements are getting deleted as the conditions are met. So , the length of Ytotal should be adjusted accordingly. But, still i am getting the error "index out of bounds" . Could anyone suggest me where i am wrong. thanks
for aa = 1:length(Ytotal)
if Ytotal(aa) > ymean+yerrorstd;
Ytotal(aa)=[];
x(aa)=[];
else
Ytotal(aa)=Ytotal(aa);
x(aa)=x(aa);
end
end
  1 件のコメント
Guillaume
Guillaume 2017 年 10 月 3 日
Ytotal(aa)=Ytotal(aa);
x(aa)=x(aa);
Are you aware that these two lines don't do anything* and could be omitted? You're just asking matlab to copy something into the same location it came from.
*unless your ytotal and x are instances of a class for which you've redefined subsasgn to perform something other than a straight copy, which would be very evil to do!

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

回答 (1 件)

James Tursa
James Tursa 2017 年 10 月 2 日
編集済み: James Tursa 2017 年 10 月 2 日
Run your loop backwards so that the reduced indexing is not a problem (not very efficient btw):
for aa = length(Ytotal):-1:1
Or just eliminate the loop entirely:
idx = Ytotal > ymean + yerrorstd;
Ytotal(idx) = [];
x(idx) = [];
  2 件のコメント
HIRAKJYOTI BASUMATARY
HIRAKJYOTI BASUMATARY 2017 年 10 月 3 日
thanks a lot sir. i solved the code using while loop . But , thanks a lot for the information. I will definitely keep it in mind
Jan
Jan 2017 年 10 月 3 日
@HIRAKJYOTI BASUMATARY: Note that shrinking an array iteratively is not efficient. James' vectorized version is much nicer and faster.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by