Filter löschen
Filter löschen

Loop problem / issue with variables

1 Ansicht (letzte 30 Tage)
mt
mt am 4 Nov. 2014
Kommentiert: mt am 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
  1 Kommentar
MA
MA am 4 Nov. 2014
what is junk? you should specify it

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Guillaume
Guillaume am 4 Nov. 2014
Bearbeitet: Guillaume am 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
  1 Kommentar
mt
mt am 4 Nov. 2014
It worked! Awesome! Much appreciated.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by