How to stop while loop with the Command Window ?

4 Ansichten (letzte 30 Tage)
Ángel Ignacio
Ángel Ignacio am 17 Feb. 2025
Kommentiert: Ángel Ignacio am 17 Feb. 2025
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.

Antworten (1)

Walter Roberson
Walter Roberson am 17 Feb. 2025
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.

Kategorien

Mehr zu Dialog Boxes finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by