How to send output to the main function from a nested callback function?
2 次查看(过去 30 天)
显示 更早的评论
Hello,
I have included a simplified version of my code.
My main function Question() has output answer that is generated inside of a nested keypress function helpme(). How can I pass answer through correctly? (Sorry for the bad naming...)
function answer = Question
hfig = figure('KeyPressFcn',@helpme);
% helpers
function helpme(src,event)
if strcmp(event.Key,'a')
disp('a key pressed')
answer = 'answer';
end
end
end
I get the following error:
Error in Question (line 3)
hfig = figure('KeyPressFcn',@helpme);
Output argument "answer" (and maybe others) not assigned during call to "E:\Documents\this_part_censored\Question.m>Question".
I have tried reading help documentation on setappdata and getappdata, but I cannot figure out how to apply them in my own function. (I would like to avoid global variables and assignin if possible.)
Thanks for any help you can offer!
0 个评论
回答(1 个)
TastyPastry
2015-10-22
This is something I struggled with when I first learned how to build GUIs. The way you have your code set up, a call to Question() runs through and does not call helpme() because the key press is never registered. In other words, Question() executes to the end and realizes that "answer" isn't assigned, so you see the error. What you actually need to do is move helpme() outside of Question() and use helpme() to return "answer".
function Question
hfig = figure('KeyPressFcn',@helpme);
end
function answer = helpme(src,event)
if strcmp(event.Key,'a')
disp('a key pressed')
answer = 'answer';
end
end
In this code, Question() is creating some GUI with the a key press callback. The callback function is the one generating the output.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Migrate GUIDE Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!