MATLAB: Stop pushbutton and while loop

pushbuttonwhile loop

Hi there 🙂
I have a small problem with this script:
function abc
uicontrol('style','pushbutton','String', 'Stop','Callback',@stopf, 'position',[0 0 50 25]);
ending=0;
while ending==0
fprintf('\n')
for k=1:2
fprintf('\b%d',k)
pause(1)
end
fprintf('\n')
end
end
function stopf
ending=1;
end
I want to stop while loop by pressing pushbutton but it doesn't work and I have no idea how to do that.
I will be grateful for any answer or solution.

Best Answer

The callback function has its own workspace. Changing a variable there does not change it in the workspace of the main function.
function abc
H = uicontrol('style','pushbutton','String', 'Stop','Callback',@stopf, 'position',[0 0 50 25]);
while ishandle(H)
fprintf('\n')
for k=1:2
fprintf('\b%d',k)
pause(1)
end
fprintf('\n')
end
end
function stopf(ObjectH, EventData)
delete(ObjectH);
end
Alternatively, when you do not want to delete the button:
H = uicontrol('style','pushbutton','String', 'Stop','Callback',@stopf, ...
'position',[0 0 50 25], ...
'UserData', 1);
...
while get(H, 'UserData') == 1
...
end
function stopf(ObjectH, EventData)
set(ObjectH, 'UserData', 0);
end
Related Question