How to convert while loop into for loop in matlab?
12 ビュー (過去 30 日間)
古いコメントを表示
i=1;
while i:length(array)
if (array(i)<=1000)
array(i)=[];
else
i=i+1;
end
end
Q1: can any body tell me how do i convert this into for loop?
Q2: does while loop by default increment while completes it iteration?
0 件のコメント
回答 (3 件)
Azzi Abdelmalek
2016 年 5 月 8 日
編集済み: Azzi Abdelmalek
2016 年 5 月 8 日
Your while loop is not correct
array=[2 4 3 1 7 8 ]
ii=1
while ii<numel(array)
if array(ii)<=5
array(ii)=[]
else
ii=ii+1;
end
end
You can do it with a for loop, but you have to know, the length of your array will decrease, this is prevented by ii-k.
array=[2 4 3 1 7 8 ]
k=0
for ii=1:numel(array)
if array(ii-k)<=5
array(ii-k)=[]
k=k+1
end
end
0 件のコメント
Image Analyst
2016 年 5 月 16 日
Don't even use any loop at all, just vectorize it
indexesToRemove = array(i) <= 1000 % Find elements that we do not want anymore.
array(indexesToRemove) = []; % Remove those elements.
0 件のコメント
Walter Roberson
2016 年 5 月 16 日
No, the only thing that while loop does by default is test the condition and execute the body if the condition is true. It does not change the value of any variable unless the code in the body instructs that it be done.
for i = length(array) : -1 : 1
if array(i) <= 1000;
array(i) = [];
end
end
This used a "trick" of sorts: it iterates backwards in the loop. Each time a value is deleted, the rest of the values "fall down to fill the hole", falling from the higher numbered indices towards the lower. If you delete (say) the 18th item, then the 19th item "falls down" to become the 18th item. If you were writing a forward for loop,
for i = 1 : 1 : length(array) %wrong
if array(i) <= 1000;
array(i) = [];
end
end
then the 19th would have fallen into the 18th and when you went on to 19, you would never looked at the value that is now in the 18th area, but with the backwards loop, only values that have already survived can "fall down" so you would not need to look at the 18th slot again.
Also, if you were looping forward, then the length would be changing, but for loops only evaluate the limits once, not every time (while loops evaluate every time), so the forward for loop would not notice that the array had become shorter, and you would run off the end of the array. This is not a problem with backwards looping: you might eliminate the last item just after you looked at it but all the previous items in the array are still going to be there, the parts you have not looked at yet (towards the beginning) are not going to get shorter "out from underneath you".
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!