Loop problem / issue with variables

4 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2014-11-4
编辑:Guillaume 2014-11-4
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by