1

I am running this on MATLAB 2014a, and the command line does not return.

a = 0;
while (1)
    a = a + 1;
    if (a ~= 2)
        continue;
    end;
end;

There is no response when I do control-C or command-. (or any other common combination of keyboard keys). How can get the script to terminate?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Pippi
  • 2,451
  • 8
  • 39
  • 59
  • Related: [What is a “tight loop”?](http://stackoverflow.com/q/2212973/2278029). Do you want want your loop to exit normally on it's own or do you want to be able to abort your script/function using control-C? – horchler Oct 08 '14 at 18:05
  • I just tried this with R2013a on a linux box and got the same behavior. I suspect one would need to be intimately familiar with the matlab interpreter in order to know why the interrupt signal does not reach it. – AnonSubmitter85 Oct 08 '14 at 18:31
  • @AnonSubmitter85: Because it's a tight loop –see the link in my comment above. The loop needs to have an explicit `pause` or call to another function (e.g., something involving graphics) that allow the command window sufficient time/resources to interrupt the running code. – horchler Oct 08 '14 at 23:44

1 Answers1

2

Instead of "continue", try "break".

Here's my reasoning:

"continue" temporarily interrupts the execution of a program loop, skipping any remaining statements in the body of the loop for the current pass only.

So it doesn't exit the loop completely, it skips any remaining code in the loop and then re-evaluates the condition of the while loop, which in your case is always true.

In contrast, break exits the loop completely.

Another way to go about it is to rewrite your loop statement, for example:

a = 0;
while a~=2
  a = a + 1;
end

Not sure why it wouldn't cease running with ctrl-c though. I expect that your script has run for such a long time that your machine might be getting progressively less responsive. Hinted by this article: http://www.mathworks.com/help/matlab/matlab_env/stop-execution.html