How to convert while loop into for loop in matlab?

12 views (last 30 days)
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?

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 8 May 2016
Edited: Azzi Abdelmalek on 8 May 2016
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

Image Analyst
Image Analyst on 16 May 2016
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.

Walter Roberson
Walter Roberson on 16 May 2016
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".

Community Treasure Hunt

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

Start Hunting!