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?
0 个评论
采纳的回答
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 个评论
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
2022-2-14
What about
if k == 0
disp("Hello World!")
elseif k == 480
disp("Bye Bye World!")
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!