Matlab: Criteria for displaying screens to subjects - matlab

I am delivering a psychology experiment in Matlab, where screens with questions will be presented to subject. The screen will also collect and display the subjects' responses. For example: Screen displays '2+3' and also displays what participant types (say, 99999), until they press enter.
GOAL: get it to stop displaying the question after 16 seconds if the participant has not yet pressed enter. (That is, stop displaying the screen if time=16sec OR if subject presses Enter.)
The problem revolves around the following code:
While CurrentTime<TimeOut
respond=GetChar() <-(Waits till user press enter)
end
So whatever the statements we add before/after capturing respond statements is not executed.
Any help on how to work around this issue would be greatly appreciated! Thanks.

Here is an example, I presented an oval as an example, you can obviously replace that with whatever your stimuli are. Enter and Return are separate keys, I wasn't sure which you're looking for, so in the example the loop looks for either.
%% include at top of experiment / block
waitForResponseSeconds = 16; % number of second to wait for a response
enterKey = KbName('enter'); % numeric code for enter key
returnKeys = KbName('return'); % numeric code for return key(s)
responseKeys = [enterKey returnKeys];
wPtr = Screen('OpenWindow', 0, 0, [0 0 400 400]);
%% within the trial loop:
hasResponded = 0;
% present the stimulus (here the window pointer is called wPtr, you may
% need to adjust this depending on what you named the window pointer.
Screen('FillOval', wPtr, [100 0 100], [0 0 400 400]);
[~, Onset] = Screen('Flip', wPtr);
while ~hasResponded && ((GetSecs - Onset) <= waitForResponseSeconds)
[keyIsDown, secs, keyCode] = KbCheck;
if any(keyCode(responseKeys))
rt = 1000.*(secs-Onset); % get response time
hasResponded = 1;
end
% Wait 1 ms before checking again to prevent
% overload of the machine at elevated priority
WaitSecs(0.001);
end
%% end of exp
sca;

Related

How to make for loops run faster - Psychtoolbox in matlab

I created a MATLAB code using Psychtoolbox to make an experiment.
Everything works as I intended but it seems the initial loading of the experiment takes too long. The task is a simple yes/no response task whether the target word('probe') appeared in the previous set of word stimuli.
I put basic intro text as an image and then wait for any keypress to start the experiment but it will take about 40 seconds to actually begin the first trial after any keystroke. I want to make it work without any delay. It should start its first trial immediately after any keystroke.
I checked the timestops with GetSecs() on numerous positions in the code and it was not anything to do with loading stimuli or initial setting of the experiment before the for loop I attached below.
To make things look simpler, I changed some of the variables into actual numbers I used. I can gurantee that it is not due to large stimuli size since it is only 1500 words. Once the for loop starts, it goes smoothly but it takes 40 seconds to actually start the first trial so I think it is something to do with a specific function in the for loop or the way I built it.
Please let me know if anything is too vague or unclear. I will do my best to make things read better.
Edit: I minimalized the code leaving only the function names used in Psychtoolbox. I left the functions I used in between loops to let you know if they could cause any delay. It will not be possible to run this without Psychtoolbox installed so I guess you can briefly examine the structure of the code.
for trial = 1:250
for i = 1:6
DrawFormattedText();
Screen();
WaitSecs(0.5);
end
DrawFormattedText();
flipTime = Screen();
WaitSecs(0.5);
DrawFormattedText();
flipTime = Screen();
rt = 0;
resp = 0;
while GetSecs - flipTime < 3
clear keyCode;
RestrictKeysForKbCheck();
[keyIsDown,secs,keyCode] = KbCheck;
respTime = GetSecs;
pressedKeys = find(keyCode);
% ESC key quits the experiment
if keyCode(KbName('ESCAPE')) == 1
clear all
close all
sca
return
end
% Check for response keys
if ~isempty(pressedKeys)
for i = 1:2
if KbName(i) == pressedKeys(1)
resp = i;
rt = respTime - flipTime;
end
end
end
% Exit loop once a response is recorded
if rt > 0
break;
end
end
if rt == 0 || rt > 3 % 3 second limit for subjects to react to the probe stimuli
DrawFormattedText();
Screen();
WaitSecs(1);
end
Screen();
vbl = Screen();
WaitSecs(1);
% Record the trial data into output data matrix
respMat{1, trial} = trial;
respMat{2, trial} = resp;
respMat{3, trial} = rt;
end

Run the for loop only once Matlab

total_Route = zeros(4,4);
tmp = evalin('base', 't'); % i initialise t in the Workspace with the value 1
if(tmp==5)
tmp=1;
end
total_Route(tmp,1) = Distance_Traveled_CM;
total_Route(tmp,2) = Hauptantrieb_Verbrauchte_Energie_CM;
total_Route(tmp,3) = Nebenaggregate_Verbrauch_Real_CM;
total_Route(tmp,4) = t;
Total_Distance_Traveled_CM = sum(total_Route(:,1));
set(handles.edit3, 'string',Total_Distance_Traveled_CM);
Total_Hauptantrieb_Verbrauchte_Energie_CM = sum(total_Route(:,2));
set(handles.edit4, 'string',Total_Hauptantrieb_Verbrauchte_Energie_CM);
Total_Nebenaggregate_Verbrauch_Real_CM = sum(total_Route(:,3));
set(handles.edit5, 'string',Total_Nebenaggregate_Verbrauch_Real_CM);
%% Index
set(handles.edit15, 'string',tmp);
assignin('base', 't', tmp + 1); % with this line i can increment "t" after each pass
guidata(hObject,handles);
Sorry that I did not explain my problem well.
#Sardar_Usama I want to run the loop only once but t should be incremented after each time I click on my Button.
# Sembei Norimaki end is at the end of my codes, have forgotten to write it in my question
#Patrik & #Dennis Jaheruddin let me explain my problem again
I created a Matrix with 4×4 Elements with the Goal to save the results of each my Variable (Total_Distance_Traveled_CM, Total_Hauptantrieb_Verbrauchte_Energie_CM etc...) after each Simulation in the element of my Matrix (See image below).
I want by pressing a button (on my GUI) to get always the sum of each Column.
Example
The first pass: t = 1--> Distance_Traveled(1,1) is 900 the GUI will take through clicking on the Button, the sum of the first column (which is 900+0+0+0) and write it in a static test.
The second pass t = 2--> Distance_traveled(2,1) is 800 the GUI will take the sum of the first column (which is 900+800+0+0) and write it in a static test and the same thing should happen with the other column.
This should continue until t = 4 i.e. until it does the same thing for each column, then it should reset.
I hope, I have explained my problem better this time and I apologize for my bad English.
I appreciate any help.
Based on your code fragment the for loop is only called once.
However, the contents of the for loop are ran for four times. (first for i=1 then for 1=2 etc..)
If you only want to run one of these options the solution is very simple:
i = 1
yourLoopContent
If i is always 0 the first time, and you always want to run it for the current i, it would also be simple:
yourLoopContent
i = i+1;
However if i may not be set properly the first time, things get messy. This is because i is by default defined as the square root of minus 1.
Therefore I would recommend you to use a different letter like t instead. Then you could do this:
if ~exists(t)
t=0;
end
yourLoopContent %Everywhere using t instead of i
t = t+1;
In general you may want to avoid i as an index to stay clear of complex number issues.
I'm not sure if I got your question correctly, but it seems to me that what you look for is a cumulative sum. This can be done either buy summing on 1:t or by using cumsum. I'm not sure why you use a loop, but if this is only for the summing then cumsum can replace that.
Here is some example in your code:
total_Route = zeros(4,4);
% I commented below what is not part of the question
for t = 1:4
total_Route(t,:) = [Distance_Traveled_CM,
Hauptantrieb_Verbrauchte_Energie_CM,
Nebenaggregate_Verbrauch_Real_CM,
t];
% the following line compute the comulative sum from the top of each
% column to every element in it, so cs_total_Route(3,2) is like
% sum(total_Route(1:3,2)):
cs_total_Route = cumsum(total_Route);
Total_Distance_Traveled_CM = cs_total_Route(t,1); % OR sum(total_Route(1:t,1))
% set(handles.edit3, 'string',Total_Distance_Traveled_CM);
Total_Hauptantrieb_Verbrauchte_Energie_CM = cs_total_Route(t,2); % OR sum(total_Route(1:t,2))
% set(handles.edit4, 'string',Total_Hauptantrieb_Verbrauchte_Energie_CM);
Total_Nebenaggregate_Verbrauch_Real_CM = cs_total_Route(t,3); % OR sum(total_Route(1:t,3))
% set(handles.edit5, 'string',Total_Nebenaggregate_Verbrauch_Real_CM);
% set(handles.edit15, 'string',t);
end
And here is a quick look on what cumsum does (with some random numbers for total_Route):
total_Route =
671 4.6012 1.0662 1
840 3.6475 0.58918 2
354 8.6056 2.1313 3
893 4.1362 2.0118 4
cs_total_Route =
671 4.6012 1.0662 1
1511 8.2487 1.6554 3
1865 16.854 3.7867 6
2758 20.991 5.7985 10
Is this what you looked for?

GetChar not waiting for response

I'm using psychtoolbox in MATLAB and I want to get a participant to rate the distortion of a string of images from 0-9.
I've tried using GetChar, but when I run the script it doesn't wait for the user to give a response but just moves onto the next screen.
Any advice on how I can fix this?
%using a loop to show images
for k=1:290
texture1(k)=Screen('MakeTexture',w,images{k});
end
for k=1:145
Screen('DrawTexture',w, texture1(k), [], leftposition);
Screen('DrawTexture',w, texture1(k+145), [], rightposition);
Screen('DrawLines', w, allCoords,...
lineWidthPix, black, [xCenter yCenter], 2);
Screen(w,'Flip');
pause(0.2);
end
%rating text
DrawFormattedText(w,'Rate distortion 0-9','center','center',[255 255 255]);
Screen(w,'Flip');
GetChar();
%press space to finish
DrawFormattedText(w,'press space to finish','center','center',[255 255 255]);
Screen(w,'Flip');
% Wait for a key press
KbStrokeWait;
% Clear the screen
sca;
There's a few things going on here: You're only looking for key presses after your loop is finished, and you're not storing the result of the key press.
GetChar is also messy (you would probably want to call FlushEvents to clear the queue, or you might run into (from help GetChar):
If a character was typed before calling GetChar then GetChar will
return that character immediately.
One alternative is demonstrated in the example below. It uses KbWait, which provides very similar functionality, with a little more work (i.e. converting the key code to a char). Additionally, it implements a 5ms delay between key checks, which helps prevent accidental key bouncing (counting single presses as multiple presses).
This example opens a small window in the upper left corner, displays the current loop iteration in the center of the screen, and waits for a single press to continue. It also records the times of the key presses in times.
Screen('Preference', 'SkipSyncTests', 2);
[win, rect] = Screen('OpenWindow', 0, [0 0 0], [15 15 400 400]);
Screen('TextSize', win, 20);
answers = cell(1, 5);
times = zeros(1, 5);
ref_time = GetSecs;
for ii = 1:5
DrawFormattedText(win, num2str(ii), 'center', 'center', [255 255 255]);
Screen(win, 'Flip');
[times(ii), key_code] = KbWait;
answers{ii} = KbName(find(key_code));
WaitSecs(0.1); %# Wait an extra 100ms for better debouncing
end
times = times - ref_time;
sca;

Repeating trials in MatLab

i'm am very new to Matlab but really want improve. For my experiment i want to show a picture which the participant response yes/no to, using two different keys (f&g) and then the next picture is presented and it repeats so onward.
Presenting the picture, using the keys works for far, but i can't get it to repeat the trial. Thus my question is how can i get the program to repeat/loop my trial?
Is there something wrong in my code so far or is there additional coding i should use?
this is my code so far
function try1_6()
cleanupObj= onCleanup(#() myCleanupFxn);
% PRETEST
% Initialize screen with black background
winID = Screen('openWindow',0, [0 0 0]);
%Parameter
backcol=255;
textcol=0;
% Load image file(s)
structimages= [];
TheImagesdir = dir('theImagesdir/*.jpg');
for i=1: length(TheImagesdir);
TheImages = imread(['theImagesdir/' TheImagesdir(i).name], 'JPEG');
% Get width and height
imageX = size(TheImages,2);
imageY = size(TheImages,1);
% Convert to texture
myTexture = Screen('MakeTexture', winID, TheImages);
% Set destination rectangle
destRect = [50 100 50+imageX 100+imageY];
%save to structure
structimages(end+1).filename=TheImagesdir(i).name;
structimages(end).destRect= destRect;
structimages(end).texture= myTexture;
end
%Make triallist
numberOfItems= [5]; %list of all possible items
Nrepeats=4;
Response=0;
TrialList=HH_mkTrialList({numberOfItems Response},Nrepeats);
%PRESENTATION
for trialnum=1:size(TrialList,1)
nitems = TrialList(trialnum,1);
Screen('FillRect', winID,backcol); % makes the screen blank
%displays text
DrawFormattedText(winID,'dkjfghaslkdfglksdjgfh','center','center',textcol);
Screen('Flip', winID)
HH_waitForKeyPress({'space'}); % waits for spacebar to be pressed
Screen('FillRect',winID,backcol);
Screen('Flip',winID);
WaitSecs(1);
%display picture
whichTheImages= randi(length(TheImagesdir)); % randomly selects image for directory
Screen('FillRect',winID,backcol);
Screen('DrawTexture', winID, myTexture, [], destRect);
Screen('Flip', winID);
HH_waitForKeyPress({'f','j'},5)
if resp==-1
break
end
TrialList(trialnum,4)= response; %records response
end
end
function myCleanupFxn()
Screen('CloseAll')
end
There are a number of problems with you code that you need to address. First of all, TrialList is used before it is declared/initialized. The Make triallist block of code seems out of place in the body of the for loop, and should probably be placed before you loop TrialList.
Your second problem is the inner for loop that loads images. Right now, it loads every image found in the directory, on every trial! There is no reason for you to be doing this, and you should be placing this for loop outside the trial loop as well. Furthermore, your original code never worked as intended, because you never save the loaded texture anywhere; myTexture is overwritten by the last image in your folder and that's the only texture you're ever gonna get. So in addition to pre-loading the images before the loop, you need to save them in a data structure so that you can use them later in your trial loop. A simple struct will work nicely here:
structImages = [];
TheImagesdir = dir('theImagesdir/*.jpg');
for i = 1:length(TheImagesdir);
TheImages = imread(['theImagesdir/' TheImagesdir(i).name], 'JPEG');
% Get width and height
imageX = size(TheImages,2);
imageY = size(TheImages,1);
% Convert to texture
myTexture = Screen('MakeTexture', winID, TheImages);
% Set destination rectangle
destRect = [50 100 50+imageX 100+imageY];
%save to structure
structImages(end+1).filename = TheImagesdir(i).name;
structImages(end).destRect = destRect;
structImages(end).texture = myTexture;
end
There are other inconsistencies in your code:
whichTheIamges is defined but not used
resp is used in the comparison if resp==-1 but is not defined
response is saved into TrialList before it is defined
Finally, the biggest problem is Screen('CloseAll', winID); is inside the trial loop, so you tear down your whole presentation platform after the first trial.
FYI, as noted in my comment wrapping your entire script in a try block is really poor practice. I suspect you do this because you want to be able to Ctrl+C mid-task, but there's a better way to do this. If you make your entire script a function then you can use the onCleanup method to execute code whenever your function exits (whether normally, by error, or by interruption). The method goes like this:
function myScript()
%//make your script a function. There is an additional advantages to doing this:
%//function performance is better than script performance.
%//blah-blah-blah
%//setup the cleanup object before opening screen
cleanupObj = onCleanup(#() myCleanupFxn);
%//open the screen
winID = Screen('openWindow',0, [0 0 0]);
%//blah-blah-blah
end
function myCleanupFxn()
%//local function, not visible outside of this file
Screen('CloseAll');
end

Matlab GUI button reaction

I am just trying to program a reaction test with a MATLAB GUI.
I've got one button which, after every click, appears at a random place and afterwards the needed time for the next click is shown.
Now I want that this button dissapears after clicking on it 10 times.
How can I program, that after the 10th click it just executes "close all;"?
Here is some code which does what you want.
As #Li-aung mentioned, I added a counter which keeps track of the number of times the pushbutton was pushed. The counter is stored in the handles structure of the figure; however you could make it a global variable for simplicity.
Here is the code with comments:
function RandomButton(~)
hFig = figure('Position',[100 100 200 200],'Visible','off');
handles.CounterText = uicontrol('Style','text','Position',[50 150 60 30],'String','Counter')
handles.DisplayCounterText = uicontrol('Style','text','Position',[50 100 60 30],'String','0')
handles.Button = uicontrol('Style','pushbutton','position',[50 50 60 30],'String','Push here','Callback',#(s,e) Push);
handles.PushCounter = 0; %// Initialize counter
movegui(gcf,'center')
set(hFig,'Visible','on')
guidata(hFig,handles)
function Push
handles = guidata(hFig);
handles.PushCounter = handles.PushCounter +1;
set(handles.DisplayCounterText,'String',num2str(handles.PushCounter));
if handles.PushCounter < 10 %// Assign condition to stop.
set(hFig,'Visible','off');
set(hFig,'Position',[1000*rand(1) 1000*rand(1) 200 200]); %// Assign random position
set(hFig,'Visible','on');
guidata(hFig,handles) %// Update handles structure. Important!
else
close all
end
end
end
Here is a screenshot of the GUI:
Hope that helps get you started!