matlabwhile-loopconditional-statementspsychtoolbox

Matlab: Criteria for displaying screens to subjects


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.


Solution

  • 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;