Loop problem / issue with variables
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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
Risposta accettata
Guillaume
il 4 Nov 2014
Modificato: Guillaume
il 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!