How to send output to the main function from a nested callback function?

3 visualizzazioni (ultimi 30 giorni)
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!

Risposte (1)

TastyPastry
TastyPastry il 22 Ott 2015
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.

Categorie

Scopri di più su Migrate GUIDE Apps in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by