Function does not return value when nested

8 次查看(过去 30 天)
Hello community,
I have encountered a slight issue with a function not returning a value when nested. My main function calls a second function, which plots some data. Within this data a button is created, which should activate a (obviously nested) callback function, which closes the figure and returns a variable, to which the second function should react. The problem is, that the nested callback function does not seem to return this value, even though it definitely is called (it closes the figure). The entire routine works, when the second function (the one creating the button, and initializing the callback) is NOT nested inside another function.
Does anyone know the reason for this, and how to solve the issue?
here is an excerpt of my nested second function:
figure(1)
d = gcf;
btn1 = uicontrol('Parent',d,...
'Position',[400 100 330 100],...
'FontSize',12,...
'String','Draw again',...
'Callback','[button_choice] = press_button_1');
uiwait
% here is where the second function breaks, when nested, as button_choice is not defined
if button_choice == 1
% do something
end
and this is the callback function
function [button_choice] = press_button_1
button_choice = 1;
delete(gcf)
end
  1 个评论
Stephen23
Stephen23 2017-1-19
编辑:Stephen23 2017-1-19
Callback functions do not return arguments. The MATLAB documentation lists ways to pass data between callbacks:
I recommend using nested functions.

请先登录,再进行评论。

回答(2 个)

Adam
Adam 2017-1-19
Callback functions cannot return arguments.
Since it is a nested function though it shares the workspace of the parent function so you can just define
button_choice = [];
(or some other default if you wish) in your main function and then just set this variable in the nested function rather than returning it.

Jan
Jan 2017-3-2

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by