Effacer les filtres
Effacer les filtres

Displayin command just once for the n number of iterations

4 vues (au cours des 30 derniers jours)
Kacper Witasinski
Kacper Witasinski le 14 Fév 2022
k = 0;
while k < 4001
if k < 480
disp("Hello World!")
else
disp("Bye Bye World!")
end
k = k+1;
end
Hello, this is funny piece of my code. I want to display information included in first conditional loop ("Hello World!") only once, when code enters the loop, not every time when k is less than 480. The same applies to the else condition. The conditions cannot change though.
Can you please show me the way?

Réponse acceptée

Benjamin Thompson
Benjamin Thompson le 14 Fév 2022
So something like this?
if k == 480
disp("Hello World!")
elseif k == 481
disp("Bye Bye World!")
end
You could also define another variable and set it to true after calling disp:
k = 0;
displayedInfo = false;
while k < 4001
if k < 480 && displayedInfo == false
disp("Hello World!")
displayedInfo = true;
else
disp("Bye Bye World!")
end
k = k+1;
end
  2 commentaires
Kacper Witasinski
Kacper Witasinski le 14 Fév 2022
works just for "Hello World!" Imagine that I have dozens of such if loops, and I want to display doznes of such messages once for one loop, at the entry, not for every iteration.
Benjamin Thompson
Benjamin Thompson le 14 Fév 2022
You can create more variables as you need. Set the variable to true once the message is displayed, and check the variable in the for loop to decide whether or not the message needs to be displayed. Give it a try and if you have more specific problems post another question.

Connectez-vous pour commenter.

Plus de réponses (1)

Alan Stevens
Alan Stevens le 14 Fév 2022
What about
if k == 0
disp("Hello World!")
elseif k == 480
disp("Bye Bye World!")
end
  1 commentaire
Kacper Witasinski
Kacper Witasinski le 14 Fév 2022
Modifié(e) : Kacper Witasinski le 14 Fév 2022
As I've mentioned, the conditions cannot change.
Now thanks to your proposal I've came up with creating additional if statement just for the value of 'k' for displaying this message, but I do not want to complicate the code with such a simple idea.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by