Loop problem / issue with variables
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
Réponse acceptée
Guillaume
le 4 Nov 2014
Modifié(e) : Guillaume
le 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!