필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
aacarey
aacarey 2015년 10월 21일
답변: TastyPastry 2015년 10월 22일
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!

답변 (1개)

TastyPastry
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.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by