Behavior of callback function?
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello,
I wanted to break out of a while-loop when a pushbutton is clicked on a figure, so I wrote the code below.
function callbackTest1
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback','pressed=1');
pressed = 0;
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
end
But, when I click the pushbutton, 'pressed=1' is displayed on command window and it does not get out of while loop.
In addition, it is suggested that 'disp('button pressed')' part can't be reached which I really don't understand.
On the other hand, the code below works as expected.
The only thing changed is that it's a script, not a function. Everything else is the same.
% callbackTest_script
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback','pressed=1');
pressed = 0;
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
Weird thing is that the same suggestion (disp('button pressed') can't be reached) is displayed but it works fine.
Finally, I figured out that I have to write the code like this.
function callbackTest2
uicontrol('Style','pushbutton',...
'String','I''m done...',...
'Position',[100 100 100 100], ...
'Callback',@press);
pressed = 0;
function press(~,~)
pressed = 1;
end
while(1)
if pressed
disp('button pressed')
break
end
pause(0.1)
end
end
1) Why does callbackTest1 not work while callbackTest_script does?
2) In callbackTest1 and callbackTest_script, why can't "disp..." be reached?
3) Anything else I should know about what's behind the behavior of callback function?
4) Is there a better way to do this than callbackTest2?
Thank you.
댓글 수: 0
채택된 답변
Walter Roberson
2020년 4월 4일
'Callback','pressed=1'
Callbacks specified as character vectors are evalin('base') and so only affect the base workspace, not local variables.
You need to use one of the techniques to share variables; Share . Your callbackTest2 is an example of using a shared variable.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Graphics Object Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!