Displayin command just once for the n number of iterations

1 次查看(过去 30 天)
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?

采纳的回答

Benjamin Thompson
Benjamin Thompson 2022-2-14
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 个评论
Kacper Witasinski
Kacper Witasinski 2022-2-14
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 2022-2-14
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.

请先登录,再进行评论。

更多回答(1 个)

Alan Stevens
Alan Stevens 2022-2-14
What about
if k == 0
disp("Hello World!")
elseif k == 480
disp("Bye Bye World!")
end
  1 个评论
Kacper Witasinski
Kacper Witasinski 2022-2-14
编辑:Kacper Witasinski 2022-2-14
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by