Ornusashas
Ornusashas

Reputation: 7

On button press, break out of while loop? - MATLAB GUI

I am having trouble breaking out of a while loop from an animated plot. Essentially, I have a MATLAB GUI with two buttons. One button starts an animated plot. The other button stops the animated plot. However, pressing the stop button does not break out of the while loop; it continues to plot. Is there something I am missing or is this simply not the way to go?

% Infinite Loop
i = 1;
flag = true;

% My attempt at breaking out of the while loop. ----------------------
if get(handles.btnStopSim, 'Value') == 1
    flag = false;
end
%---------------------------------------------------------------------

while flag
     % Update Point 
     set(hLine, 'XData', xInit(1, i), 'YData', yInit(1, i)) 
     set(hLine2, 'XData', xInit(2, i), 'YData', yInit(2, i))
     set(hLine3, 'XData', xInit(3, i), 'YData', yInit(3, i))
     set(hLine4, 'XData', xInit(4, i), 'YData', yInit(4, i))
     set(hLine5, 'XData', xInit(5, i), 'YData', yInit(5, i))
     set(hLine6, 'XData', xInit(6, i), 'YData', yInit(6, i))
     set(hLineTarget, 'XData', Target(1), 'YData', Target(2))

     drawnow

     pause(delay)
     i = rem(i + 1, numPoints) + 1;
     if ~ishandle(hLine), break;
     end
     if ~ishandle(hLine2), break;
     end
     if ~ishandle(hLine3), break;
     end
     if ~ishandle(hLine4), break;
     end
     if ~ishandle(hLine5), break;
     end
     if ~ishandle(hLine6), break;
     end
end

The stuff in the while loop is just trajectory data. Standard stuff...

Please let me know if more information is needed.

Thank you!

Upvotes: 0

Views: 3069

Answers (1)

YisasL
YisasL

Reputation: 335

That is sequential. If you want to quit the while loop, you should check/change the flag in the callback of the button. Of course, define flag as global to be accessed from both functions.

Something like

function btnStopSim_Callback(hObject, eventdata, handles)\
    global flag
    flag = false;

for the button, and the rest of the code in a main function, for instance.

Upvotes: 2

Related Questions