How to make a infinite while loop that stops on users command.

3 views (last 30 days)
Hello, I am currently trying to figure out how to make a while loop that will run indefinitely and only stop when the user is ready to stop the program. I really don't get how to correctly set up the matlab while loop. so far I have something like this to make it run forever. This might not work, I haven't tested it. But the idea is it runs forever.
n=3 While n>2 -code end
If matlab lets you do this I would like to set a key, lets say N, so when the user presses it the while loop stops. Any suggestions on how I can do this or something similar?
Thanks for the help, Brad

Answers (2)

Jon
Jon on 10 Aug 2015
It's not the prettiest, but the simplest would be to press control+c, which halts any code that is executing. Also, this same question has been asked and answered before: https://www.mathworks.com/matlabcentral/newsreader/view_thread/271516

Brendan Hamm
Brendan Hamm on 10 Aug 2015
Might be a bit more than you are looking for, but there is such a thing as a Key-Press Function (KeyPressFcn) for figures. This could be used in your program, you'd likely want some text to let the user know what to do though to stop it. There are many other ways using graphical objects to do this as well. Cleve Moler (the original MATLAB creator) has a file fern.m which has an interruptible infinite loop.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!