Displayin command just once for the n number of iterations

1 view (last 30 days)
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?

Accepted Answer

Benjamin Thompson
Benjamin Thompson on 14 Feb 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 Comments
Benjamin Thompson
Benjamin Thompson on 14 Feb 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.

Sign in to comment.

More Answers (1)

Alan Stevens
Alan Stevens on 14 Feb 2022
What about
if k == 0
disp("Hello World!")
elseif k == 480
disp("Bye Bye World!")
end
  1 Comment
Kacper Witasinski
Kacper Witasinski on 14 Feb 2022
Edited: Kacper Witasinski on 14 Feb 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.

Sign in to comment.

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!