Why do I receive "Index exceeds the number of array elements. Index must not exceed 7." when trying to remove indices that are followed directly by a zero using a for loop.

3 ビュー (過去 30 日間)
Annika Colmer
Annika Colmer 2022 年 10 月 21 日
編集済み: Torsten 2022 年 10 月 31 日
here's the function I am trying to use
function removed = removeData(vec)
vec1 = vec;
for x = 1:length(vec)
if vec(x+1) == 0
if vec(x)~=0
vec1(x)=[];
end
end
end
removed = vec1;
end
and heres the code I am trying to test it on
ans1 = removeData([2 3 0 0 7 8 0])
  1 件のコメント
Torsten
Torsten 2022 年 10 月 31 日
編集済み: Torsten 2022 年 10 月 31 日
Maybe you should first explain what "removeData" is supposed to do with "vec".
From your code, it should remove the nonzero number preceeding a sequence of zeros, but I'm not sure if this is really what you want to achieve.

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

回答 (1 件)

Jon
Jon 2022 年 10 月 21 日
Your loop variable x goes from 1 to the length of the vector.
In line 4 you try to assign vec(x+1), on the last iteration x = length of the vector so vec(x+1) is one element beyond the last element in the vector.
By the way it is more conventional style to use i,j,k,l,m for integer indices, x is usually used for real values, e.g 4.3216

カテゴリ

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