How to collect and show answers captured by using key press function (keypressfnc)?
Show older comments
I have a survey with n questions. Each question will can be answerd with yes or no. To caputure the answer of each individual questions I would like to use the key press function. If the subject's answer to the current question i is no, the subject presses the left arrow key and a "0" will be stored in an array at the position (i,1). If the subject's answer to the current question i is yes, the subject presses the right arrow key and a "1" will be stored in the array at the position (i,1). When all questions are answerd, the answer-array has n entries.
The desired output is to display the completely filled answer-array (size nx1).
I do not get the filled array and i can't display it, because of the following problems:
1) During the iteration I can give answers by using left or right arrow key, but the values are not assigned to i. Therefore the answers are not stored an the iteration does not stop after n answers.
2) Pressing any other key than left or right arrow key and then pressing left or right arrow key creates n copies of the given answer. Infinite answers can be given, but I can not use the command window anymore and the only way to stop the code is by closing Matlab.
So, please help me: How do I have to to change my code to get my individual answers, store them at the correct position into the array, stop the iteration when i have all n answers and end my function properly?
survey;
function survey() % outer function
hkey = figure;
set(hkey,'KeyPressFcn',@(src, evnt) UserFeedback(src, evnt));
waitfor(hkey);
function UserFeedback(~,evnt) % inner function
n = 5; % total number of questions
answers = zeros(n,1); % array where all n answers will be saved
for i = 1:n % answer all n questions individually until every question was answerd
if strcmpi(evnt.Key,'leftarrow') % answer is no
userresponse = 0; % write 0 into array at (i,1)
answers(i,1) = userresponse;
nope = ['The answer of question ', num2str(i), 'is: NO.'];
disp(nope) % display response
pause; % go to next question
elseif strcmpi(evnt.Key,'rightarrow') % answer is yes
userresponse = 1; % write 1 into array at (i,1)
answers(i,1) = userresponse;
yeah = ['The answer of question ', num2str(i), 'is: YES.'];
disp(yeah) % display response
pause; % go to next question
end % if-conditions
end % for-loop
disp('All answers have been captured.') % notification that survey in for-loop has been complete
disp(answers); % desired output - results of survey: all n given answers
end % inner function
end % outer function
Accepted Answer
More Answers (0)
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!