MATLAB: How to break a while loop in a gui toggle button callback

breakcallbackguiMATLABwhile

I have created a GUI with a pushbutton set to toggle mode, and within the callback for the buttton, I have a while loop running. The while loop begins after I press the GO button ("pushbuttonGO" in the code), and I am trying to get it to break by sensing the false value of a boolean variable in the handles structure (handles.RUNNING -> false).
This method is not working. When I press the button to stop, the while loop continues.
Can anyone tell me either how to correctly sense (e.g. by correct syntax for getting updated handles data) the boolean handles.RUNNING within this loop, or where to move the while loop so that operation stops when I press the toggle button again.
The code for the pushbutton callback is below. I am not sure how to attach both the .m and .fig files here.
Thank you.
% --- Executes on button press in pushbuttonGO.
function pushbuttonGO_Callback(hObject, eventdata, handles)
% hObject handle to pushbuttonGO (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject, 'Value')
handles.RUNNING = true; %toggle bool on
guidata(hObject,handles); %update handles

set(handles.pushbuttonGO,'BackgroundColor',[0.9,0,0]);
set(handles.pushbuttonGO,'String','Running');
set(handles.editTextNotice,'String','pushed GO');
pause(0.3);
timeInterval = 0.5; %s
set(handles.editTextInterval,'String',sprintf('%.2f',timeInterval));
while 1
X = rand(5000,30*4);
Xstr = sprintf('%.1f,',X(1:10,:));
set(handles.editTextData,'String',Xstr);
pause(timeInterval);
handles=guidata(hObject); %PROBLEM?
if ~handles.RUNNING %! Never breaks
break
end
end
else
set(handles.pushbuttonGO,'BackgroundColor',[0,0.9,0]);
set(handles.editTextNotice,'String','OFF');
set(handles.pushbuttonGO,'String','Press to Run');
guidata(hObject, handles); %update handles
handles.RUNNING = false; %toggle bool off
end

Best Answer

Here is an example. Basically you have to flush the event queue by calling DRAWNOW or PAUSE to check if the state of the button has changed. Try this out.
function [] = gui_toggle()
% How to stop a while loop with a toggle button.
S.f = figure('name','togglegui',...
'menubar','none',...
'numbert','off',...
'pos',[100 100 300 150]);
S.t = uicontrol('Style','toggle',...
'Units','pix',...
'Position',[10 10 280 130],...
'CallBack',@callb,...
'String','No Loop');
movegui('center')
function [] = callb(varargin)
set(S.t,'string','Looping!')
drawnow
while 1
sort(rand(1010101,1)); % Put your code here.
drawnow
if ~get(S.t,'value')
set(S.t,'string','No Loop')
break
end
end
end
end
Related Question