# Loop through a vector with changing legth

3 ビュー (過去 30 日間)
Alex De C 2018 年 3 月 22 日

Hello everyone. I want to loop through a vector, say z, and at each iteration remove some elements from it, using something like
z = z(abs(z-z(i)>=1))
My problem is, I don't know how to form the loop. I tried using
for member = z
but then again, I need to do calculations with each element so that doesn't work. Can anyone help me?

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

### 採用された回答

KL 2018 年 3 月 22 日
why not use a while loop?
idx = 1;
while idx<=numel(z)
%do something
z = z(abs(z-z(idx)>=1));
idx = idx+1;
end
##### 2 件のコメントなしを表示なしを非表示
Alex De C 2018 年 3 月 22 日
Ok yes I feel so stupid now :D
Stephen23 2018 年 3 月 22 日

"I need to do calculations with each element so that doesn't work"
Neither does this answer. This answer does not "do calculations with each element" as the question requests, it actually misses calculating with elements that follow any removed element that happens to be one position more than the current index (because the element removal and the index increment both conspire against its author).
Compare with this simple example, following the same concept, to remove all even values from z:
z = [1,1,2,2,3,3,4,4,4,5];
idx = 1;
while idx<=numel(z)
if mod(z(idx),2)==0
z(idx)=[];
end
idx = idx+1;
end
but at the end there are still even values in the vector!:
>> z
z =
1 1 2 3 3 4 5
Actually it did not test all elements to check if they are even! In general not all elements get tested by this algorithm although in some special cases they might be.
See Jan Simon's answer for a correct analysis of this problem.

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

### その他の回答 (1 件)

Jan 2018 年 3 月 22 日
A loop over the elements of a vector cannot work, if you remove elements of the vector, except if you process the elements from the end to the start and remove only elements, which are after the current element.
z = rand(1, 10)
for k = 9:-1:1
if z(k) < 0.5
z(k+1) = [];
end
end
This cannot work, if you run it in the opposite direction from 1 to 9.
So what does "loop through a vector" exactly mean, if you remove elements? It cannot be an "element by element". What should happen exactly with the vector? You have to define this clearly, before it can be implemented.
##### 1 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
Alex De C 2018 年 3 月 22 日
Thanks for the reply. The thing is, I calculate something for each element and depending on the result, i remove it and its ajdustents. I will try it with a while loop, I think it will work

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

### カテゴリ

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