I'm trying to update a matrix with response times inside a function within KeyPressFcn in a figure. how can i do that?
my code (not working, 'responses' doesn't get updated):
hf=figure('Toolbar','none','Menubar','none','NumberTitle','off',...
'Units','normalized','position',[0 0 1 1],'Color',[1 1 1]);
for trial = 2:trial_num
tic
set(hf, 'KeyPressFcn', ...
@(fig_obj , eventDat) myFunction(fig_obj, eventDat, trial, same_or_not, yes_no,toc, responses));
pause(0.05)
axis off
set(letter_text,'String',trial_letters(trial))
pause(0.75)
axis off
set(letter_text,'String','')
set(yes_no,'String','')
end
function myFunction(~, eventDat, trial, same_or_not, yes_no, toc, responses)
key = eventDat.Key;
if (key == 'space')
responses(trial,1) = 1;
responses(trial,4) = toc;
if (same_or_not(trial) == 1)
set(yes_no,'String','yes')
set(yes_no,'Color',[0 1 0])
else
set(yes_no,'String','no')
set(yes_no,'Color',[1 0 0])
end
end
end
Thanks

1 commentaire

Stephen23
Stephen23 le 23 Fév 2018
Modifié(e) : Stephen23 le 23 Fév 2018
As an aside, for callback functions it is often simpler to use the cell array syntax rather than defining an anonymous function:
set(hf, 'KeyPressFcn', {@myFunction, trial, same_or_not, yes_no,toc, responses});
The called function remains the same.

Connectez-vous pour commenter.

 Réponse acceptée

Stephen23
Stephen23 le 23 Fév 2018
Modifié(e) : Stephen23 le 23 Fév 2018

0 votes

MATLAB is pass-by-value, so when you change responses inside the callback function it does get changed... but only inside that function workspace. But because you never save or allocate this value to anything then it is simply discarded when that callback finishes. I think this may be what you are referring to when you write "not working, 'responses' doesn't get updated".
If you want the changed responses array to be returned to the calling function's workspace then you need to specify this: you will need to use one of the methods specified in the MATLAB documentation for passing data between callback functions:
I would recommend that you use nested functions, which are simple, intuitive, and easy to debug. For your code it would also mean that you do not need to pass those arrays as input arguments:
function [...] = mainfun(...)
...
responses = [...];
...
for trial = ...
...
set(hf, 'KeyPressFcn', {@myFunction, trial});
...
end
...
function myFunction(~, eventDat, trial)
responses(trial,...) = ...
end
...
end
When the callback is called it can access all of the variables in the main function's workspace. The only argument that you will need to pass explicitly is the loop iteration variable, as my code shows.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by