How to stop while loop with the Command Window ?

4 ビュー (過去 30 日間)
Ángel Ignacio
Ángel Ignacio 2025 年 2 月 17 日
コメント済み: Ángel Ignacio 2025 年 2 月 17 日
I would like to create a menu that executes a task (for example, an increment) and stops when the value 0 (i = 0) is entered through the matlab "Command Window".
-------------------------------------
Code attached below:
i = 1;
while i ~= 0
disp(i)
pause(1)
i = i+1;
end
-------------------------------------
The problem comes when i enter the value " i = 0 " through the "Command Window" and the while loop does not stop.
What solution can i apply to make it works as i would like?
Thank you very much in advance.

回答 (1 件)

Walter Roberson
Walter Roberson 2025 年 2 月 17 日
Your existing code never reads from the keyboard, so the keyboard is effectively locked out during execution (well, not locked out, but data entered on the keyboard goes into the keyboard buffer, which is not checked until the code is finished.)
You have a few choices:
  • put an input() command into the loop, forcing the user to enter something every iteration of the loop
  • rework the code to use something like waitbar . If the user x's to close the waitbar, then the waitbar object will become a handle to a deleted figure, which can be detected by using isvalid() on the handle to the waitbar.
  • make sure the code is in a file, and run the code under the debugger. At the time you want the code to stop, press the debugger Pause button, which will cause the code to wait at the keyboard at the next available opportunity. Enter the i = 0 and tell the debugger to resume.
  1 件のコメント
Ángel Ignacio
Ángel Ignacio 2025 年 2 月 17 日
Ok, thank you very much :)
I'll try it and i tell you.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDialog Boxes についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by