Loop problem / issue with variables

2 views (last 30 days)
mt
mt on 4 Nov 2014
Commented: mt on 4 Nov 2014
Hi all, I am having a little issue with my loop statement here. I want to end it when i reaches limit. If I run the code at this state and the workspace shows that limit is 5746 (which is supposed to be) but i goes on until 5747! What am I doing wrong?
i = 1;
k = 1;
sum = 0;
limit = size(junk,1); %returns 5746
while i<limit
if isequal(leapyear(year(i)),1)
if isequal(month(i),2)
for one = day(i):eomday(year(i),month(i))
sum = sum + data(i);
i = i + 1;
end
mean(k,1) = sum/eomday(year(i),month(i-1));
sum = 0;
k = k + 1;
else
for two = day(i):eomday(year(i),month(i))
sum = sum + data(i);
i = i + 1;
end
mean(k,1) = sum/eomday(year(i),month(i-1));
sum = 0;
k = k + 1;
end
for three = day(i):eomday(year(i),month(i))
sum = sum + data(i);
i = i + 1;
end
mean(k,1) = sum/eomday(year(i),month(i-1));
sum = 0;
k = k + 1;
else
for four = day(i):eomday(year(i),month(i))
*sum = sum + data(i);*
i = i + 1;
end
mean(k,1) = sum/eomday(year(i),month(i-1));
sum = 0;
k = k + 1;
end
end

Accepted Answer

Guillaume
Guillaume on 4 Nov 2014
Edited: Guillaume on 4 Nov 2014
Your code boils down to:
while i<limit
for onetwothreefour=something:another
i = i + 1
end
end
which, from the point of view of i is equivalent to:
while i<limit
i = i + (another - something) + 1;
end
Thus on each loop, i increases by an arbitrary value, eomday(...)-day(i), and it's no surprise that it can go over the limit. To stop that happening, in each for loop, you need to add:
if i>=limit
break;
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!