MATLAB: How to pause and restart a script that is executing a long FOR loop in MATLAB

functionMATLABpauserestartscript

How can I pause and restart a script that is executing a long FOR loop in MATLAB?
I want to pause and restart a script that is executing a long FOR loop so that I may do other things on my machine.
For example, if my script looks something like:
<Beginning Code>
for x = 1:1000000
<Iterative Code>
end
<Final Code>
I want to be able to stop this FOR loop at some time, perform some unrelated tasks, then restart at its current iteration.

Best Answer

To stop and restart a FOR loop in the following form:
<Beginning Code>
for x = 1:1000000
<Iterative Code>
end
<Final Code>
Use Ctrl+C to stop the iteration. If Ctrl+C does not stop the loop right away, place a DRAWNOW command within your iterative code. This will allow MATLAB to check for a Ctrl+C command during every iteration.
After the FOR loop has been halted, type:
save TempData
This saves the current workspace to a MAT-file. At this point, you can do any task you would like within MATLAB. When you are ready to restart the FOR loop, create and run a similar script file comprised by the code:
load TempData
N = x;
for x = N:1000000
<Iterative Code>
end
<Final Code>