How to use pushbutton to stop a loop?
5 次查看(过去 30 天)
显示 更早的评论
Hello All, I am working on the GUI of my code. I have start code which works in for loop. More the user inputs bigger loops. So I want to have a stop button which will close the process at the loop when it is pressed. So far I tried this with no luck:
For Stop button I have kept this:
function stop_Callback(hObject, eventdata, handles)
% hObject handle to stop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
I1.kill=1;
set(handles.stop, 'UserData', I1);
Now in my start button call back I have this:
I1= get(handles.stop, 'UserData');
And within the for loop I have added this:
for ii = 1:length(fVal)
if I1.kill~=1
I know this is not correct and that's why I am getting:
Attempt to reference field of non-structure array.
But I would like to know a work around to make stop button.
0 个评论
采纳的回答
Geoff Hayes
2016-7-21
adi - the error message is probably being generated because you are trying to access a field of a structure that has not yet been defined (since the invoking the stop button occurs after pressing start). Another problem with the above is that in the start button callback, you call
I1= get(handles.stop, 'UserData');
outside of the for loop and so I1 would be static for the remainder of the iterations. You would need to continually update this local variable on each iteration of the for loop to see if there has been a change.
An alternative to the above is to just use the handles structure. In your stop button callback do
function stop_Callback(hObject, eventdata, handles)
handles.endLoop = true;
guidata(hObject, handles);
Now, in your start button callback, you would do
function start_Callback(hObject, eventdata, handles)
% do stuff
for ii = 1:length(fVal)
% get the updated GUI handles
guiHandles = guidata(hObject);
if ~isempty(guiHandles) && isfield(guiHandles,'endLoop') && guiHandles.endLoop == 1
guiHandles.endLoop = 0;
guidata(hObject,guiHandles);
% exit the loop
break;
end
% do other stuff
% pause the loop to allow other callbacks to fire
pause(0.01);
end
The pause is important because without it, the above for loop is "tight" and won't allow any interruption...so you could press the stop button as many times as you want but there would be no effect until the loop had finished.
So try updating the handles structure instead, get the latest on each iteration of your for loop, and do the pause to allow the stop callback to fire.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Interactive Control and Callbacks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!