MATLAB: How to manualy break a for loop but continue with the rest of matlab code execution

manual break for loopMATLAB

How to manually break a for loop in matlab during execution so that the program get out of loop and continue the rest of the code after the for loop?
I define a for loop for 2000 iterations. Each iteration needs to perform an expensive function evaluation for a few minutes which give me a new point (x,y) to dynamically update my line plot. I am going to dynamically plot (x,y) points. Whenever the user decides not to continue with the for loop based on the shape of the dynamic plot, he /she should be able to break the loop and continue with next piece of codes comes after the loop. Note that Ctr+C just kills all the codes.

Best Answer

It is possible, but not trivial. Matlab figures is a one type of gui. For these there are some defined processes that can do what you want to. Speaking lower level, you can say that you pushes and pulls event from an event queue, that most likely runs in a separate thread (maybe windows iostream?). This is implemented in the matlab gui elements in the form of callback functions. You do not need to think about it yourself, since the callback functions are already defined. What you must do however is to define an action that will occur when the callback is triggered. This is done in this simple example.
First write a function myCallback that will change color of the plotted line when triggered:
function myCallback(hObject,eventdata)
c = 'krym';
n = randi([1,4],1);
ch = get(gca,'Children');
set(ch,'Color',c(n));
Then create a plot and tell the gui to perform myCallback when triggered:
plot(1:10,'LineW',2)
set(gcf,'ButtonDownFcn',@myCallback)
This will change line color of the plotted line when I click the mouse on the figure, but outside the axes. You may instead want to write a function calling close when some action is triggered and break then break the loop if the figure is closed.
Related Question