Exiting infinite loop on command
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
The issue is this: i have an infinite loop defining a short, repeating animation displayed as images in CData of a functionless button called imgwindow. i essentially want to exit it on command, so that the animation stops when the user presses a button. These are the essential code elements:
%imgs loaded in the openfcn
handles.im0 = imread('im0.png');
handles.im1 = imread('im1.png');
handles.im2 = imread('im2.png');
handles.im3 = imread('im3.png');
function startbutton_Callback(hObject, eventdata, handles)
handles.stop = 1;
while handles.stop = 1
for i = 1:3
if i == 1
set(handles.imgwindow,'CData',handles.im1)
elseif i == 2
set(handles.imgwindow,'CData',handles.im2)
elseif i == 3
set(handles.imgwindow,'CData',handles.im3)
end
pause(0.1)
end
end
guidata(hObject,handles);
function stopbutton_Callback(hObject, eventdata, handles)
handles.stop = 2;
set(handles.imgwindow,'CData',im0)
guidata(hObject,handles)
what ends up happening is that im0 does indeed show up, but then the animation resumes. I know that if interrupted in the middle of performing a callback, the original fcn will hold off at a pause, and then resume. I was hoping redefining the stop variable in this pause would then cause it to exit the loop, but that has not been the case. any help? Thanks, Alex
0 comentarios
Respuestas (4)
TAB
el 27 de Abr. de 2012
Use global variable as a flag to break the loop. Global variables always retains its value belween the function calls.
% --- Executes on button press in Start Button.
function Start_Callback(hObject, eventdata, handles)
global loopFlag;
loopFlag = true;
while true
if(loopFlag==false)
break;
end
disp('Hello');
pause(1);
end
% --- Executes on button press in Stop Button.
function Stop_Callback(hObject, eventdata, handles)
global loopFlag;
loopFlag=false;
0 comentarios
Walter Roberson
el 27 de Abr. de 2012
Just before the end of your "while" loop, inside the loop, add
handles = guidata(hObject);
(You probably don't need the guidata(hObject,handles); call after the loop though.)
2 comentarios
Ver también
Categorías
Más información sobre Animation en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!