Problem of using "assignin" during figure callbacks
15 views (last 30 days)
Show older comments
Hi every member,
Overall, I want to get a output from a figure callback after the figure closed. I am doing it by using "assignin". But during I used it, I found a curious problem. Even by assignin('caller'), which is suppose to be a function workspase, the argument always be sent to the base workspace. I have no idea why it happens in this way. Following is my code to illustrate my problem in details. The variable "rx" and "imgx" is a contrast to show my problem.
>> make_img % this is the input command in matlab command line
% this function is to make a "img" variable and calling "test" function
function make_img
radius=100;
c0=[radius+1,radius+1];
[X,Y] = ndgrid(1:2*radius+1) ;
img = zeros(2*radius+1);
img(sqrt((X-c0(1)).^2 + (Y-c0(2)).^2) <= radius) = 1;
test(img) % call "test"
end
% this is the called function
% it suppose to give the "caller" two variable, rx and imgx, not to the base
function test(img)
r=20;
assignin('caller','rx',r)
h=imshow(img);
fig = gcf;
fig.UserData.img=img;
fig.WindowKeyPressFcn=@key;
function key(fig,~)
img=fig.UserData.img;
a=fig.CurrentCharacter;
if isequal(a,'q')
assignin('caller','imgx',img);
delete(fig)
return
end
end
end
The output in base workspace is suppose to be none. But the "imgx" exist and "rx" not. It seems the caller of the callback is always the base workspace? I am confused about it. If it is so, how could I get a output after the figure deleted in the subfunction workspace?
Thank you.
7 Comments
Stephen23
on 5 Jun 2019
"It is a pity could not accept your comment as an answer"
You can now :)
I am glad that it helped!
Accepted Answer
Stephen23
on 5 Jun 2019
You just need to add waitfor to your code:
function out = test(...)
out = [];
fgh = figure(...);
...
function mycallback(...)
out = 'hello world';
end
...
waitfor(fgh) % return only when figure is closed.
end
More Answers (1)
Jan
on 4 Jun 2019
Exactly: Callbacks are called from the base workspace.
"how could I get a output after the figure deleted in the subfunction workspace?"
It depends on where you want which output. You can simply write in a message in the command window from inside the key() function. But if you want to create a variable in the base workspace, the program design is inefficient. Using the base workspace as a collector of variables is not smart. Better create a GUI and keep it open as long as the processing is going on. Then store the variables inside the GUI, e.g. using guidata. This allows you e.g. to run multiple instances of the code without collisions by a polluted base workspace.
See Also
Categories
Find more on Interactive Control and Callbacks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!