Function does not return value when nested

8 views (last 30 days)
Max
Max on 19 Jan 2017
Answered: Jan on 2 Mar 2017
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 Comment
Stephen23
Stephen23 on 19 Jan 2017
Edited: Stephen23 on 19 Jan 2017
Callback functions do not return arguments. The MATLAB documentation lists ways to pass data between callbacks:
I recommend using nested functions.

Sign in to comment.

Answers (2)

Adam
Adam on 19 Jan 2017
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 on 2 Mar 2017

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!