I'm trying to end the program once my variable reaches a certain value. I used a conditional, but my program won't stop?
    5 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Maryam Ansari
 le 2 Fév 2016
  
    
    
    
    
    Réponse apportée : BerendBotje
 le 2 Fév 2016
            This is a part of my code. I put my if statement outside the while loop. I don't understand how I can get it to stop once "population" = 7.14*10^9.
while n < nFinal + 1 %%will continue until n = nFinal (made it nFinal + 1 so population is calculated for nFinal)
      populationArray = ones(1,nFinal); %%made a an array to preallocate with
      for i = 1:nFinal
          population = zombie_interest(P,r,n); % do calculation using T function from zombie_interest
      %%fprintf('population on Day %d is %d\n',n,population); % prints out population for each day
          populationArray(1,i) = population; %%this replaces ith column with the population value
          n = n+1; %increases n by 1 for each day
      end
end
if population == 7.14*10^9
            display(n);
            return;
end
display(n);
display(population);
1 commentaire
  random09983492
      
 le 2 Fév 2016
				
      Modifié(e) : random09983492
      
 le 2 Fév 2016
  
			You are initializing the populationArray inside of the while loop. This means that every time the while loop executes, your array is reset to all ones. Initialize this array outside of the while loop.
Réponse acceptée
  BerendBotje
 le 2 Fév 2016
        From what you've posted, this should work just fine. It's not your entire code, though. Without the entire code, it's hard to find errors like this.
Anyway... you might be running into a problem because you have an inner loop that runs to nFinal, while your outer loop runs to nFinal + 1. This will make your outer loop actually loop to 2*nFinal, because the inner loop will be executed twice (each time nFinal times).
If that doesn't answer your question, post your entire code.
0 commentaires
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!


