Part 3

In this section we’ll cover the basics of PsychToolbox in Matlab


Introduction to PTB

In this section we’ll cover the basics of PsychToolbox

In the following set of exercises we’ll build up a simple experiment.

This first step is the set up phase.

The setting up stage will include a number of steps. For example, you may need to:


To determine which keyboard to use we’ll use the GetKeyboardIndices function.

Using this, you’ll be able to find the code for the keyboard you want to you.


Next, we’ll determine which screen to you. We can use Screen('Screens') to do this.

If you only have one monitor plugged in then you’ll only have one number, otherwise you’ll have two or more.


So far, we’ve just been typing commands into the command window, but we’ll want to put them all in a script. Let’s create a script to hold our task.

Create a new screen and copy the above command into it. In case we have multiple keyboards and/or multiple monitors, we’ll add a couple more lines of code to hold the indices of our primary monitor and primary keyboard.


The next step is to create a unique subject code. We have a few options here.

First, we could use the input function to get the experimenter enter a subject code. For this, we could use something like the code below.

Or we would generate a random id, and append the date and time so that we ensure it is unique.

Here’s an example of a function that does that.

Download MakeSubjectID.m


The next thing we could do, is to use the subject id code to construct a filename that will hold the data. We can use string concatenation to do this. For example, we could try something like this.

Now that we have a filename, we could, if we wanted to, check whether this file already exists. We could use something like the snippet below to do this.

What this code does is it produces an error, and stops the code running, if the file already exists. If the file doesn’t already exist, then it just proceeds without doing anything.

We can add our subject id generating code to our script now.


The next thing we’ll do is set up our trial structure.

Our task is going to be a word discrimination task where participants will press one key when they see the word “DOG” and another key when they see the word “CAT”.

For each trial we’ll need to know the following information.

  1. The stimulus that will be presented

  2. The expected response

And we’ll need to be able store

  1. The actual response

  2. The reaction time.

I recommend writing a function to generate your trial structure. Here’s an example of what that function might look like for our ‘DOG’/‘CAT’ task.

Download MakeTrials.m

The trial table is stored in a struct (see the cheetsheat and Part 1 for a refresher on structs). Using a struct is easier then storing information in a cell array or matrix because we can use the field names to access the information we want.


We now have our trial structure and we have the information we need about which screen we’ll use and which keyboard we’ll use. Now let’s actually open up a screen!

Since we’re just testing stuff out, we’ll only open a small screen in the corner of our monitor. We’ll be able to change it later. To open up a small screen we can use the following code:

If you want to close the screen down, just run sca at the command window.


Now that we have screen open, let’s add some text to it! This text will be the instructions given to the participant.

We’ll use Screen('TextSize'...) to set the size of the text, and DrawFormattedText to actually draw the text.

But remember, you won’t see anything until you flip the screen.


We don’t want to show the instructions for ever. So let’s wait until a key is pressed and then we’ll clear the screen.


We’re now onto the main part of the experiment. In this part, we’ll loop over the trials and actually display the words ‘DOG’ and ‘CAT’ on the appropriate trials.

One each iteration of the loop we’ll have to do the following things.

  1. Select a stimulus from the trial structure

  2. Show a fixation cross

  3. Display the stimulus

  4. Collect a response.

But before we do all this, we’ll need to know how many times to loop. Do do this, we’ll use the size/length function to set up our loop. We could do something like the following:


Before we can start putting stuff inside the main trial loop, we’ll still need to add a little more code which will help us to collect responses.

We’ll use KbQueueCheck() to collect the responses because we want to have very accurate timing.

The steps for using KbQueueCheck() (from the session 1 slides) are:

  1. Create the queue: KbQueueCreate(DEVICE_TO_USE)

  2. Start the queue: KbQueueStart(DEVICE_TO_USE)

  3. Flush the queue: KbQueueFlush(DEVICE_TO_USE)

  4. Check the queue: KbQueueCheck(DEVICE_TO_USE)

  5. Stop the queue: KbQueueStop(DEVICE_TO_USE)

  6. Release the queue: KbQueueRelease(DEVICE_TO_USE)

Steps 1 & 2 will be before the loop, 3 & 4 inside the loop, and 5 & 6 after the loop

Add this code together with our loop will look something like this


Now we can start with the main trial code. One of things we’ll need to do is present a fixation cross. Let’s write a function to do this, because that’ll make our life easier.

Download DrawFixationCross.m


Now let’s add some code that selects the stimulus from the trialTable.

Something like the following will do the trick.

Next we’ll use our DrawFixationCross function to draw a fixation cross.

Then we’ll flip the screen to show the cross

Then we can pause for some amount of time before showing the actual stimulus. You could vary this from trial to trial (this would be particularly important if this was an experiment for EEG), but we’ll keep it simple and just pause for 0.5 seconds.


The next step of the process is to show the stimulus and record the response time. We’ll start by adding the stimulus to be the back buffer, but we won’t show/flip it yet.

Then we’ll flush keyboard queue to make sure there aren’t any key presses in there.

Now we can actually flip the screen and measure the time of the flip.


Now that the stimulus is on the screen we can start checking for key presses. I like to write a little function to collect responses, because it’s a bit of code that you’ll write over and over each time you program up a new experiment.

Here’s an example of what that might look like:

Download CollectResponses.m

The code in this function will carry on running over and over until a key press is detected. So following the call to this function, we’ll call another Flip to clear the screen.


Next we’ll calculate the reaction time and record it in our trialTable.

We can add all this to our experiment script.

The responses are just added as new fields in the trialTable struct


We now have enough for a basic experiment. Only a couple of things remain. First, is to save the trialTable. We can save it as a .csv file.

Because the built in functions in Matlab can’t write out .csv files with column headings and mixed data types, we’ll use this custom function to write the trialTable struct to a .csv with column headings.

We can use this function to actually write out the .csv file.

Download writeStruct2csv.m


The very last thing is to close down the PsychToolbox screen. The last line of the experiment should be

An example experiment

Download MyPTBTask_demo.m

Demo task files

You can download all the files for the demo task by clicking Download here

Reading and writing data

In this section we’re cover how to get data into and out of Matlab. In particular, we’ll learn about data formats that work well with R, Python, and SPSS.


Let’s start off by loading in some data. We’ll load up a .csv file. Download data.csv

Once you’ve downloaded the file, try and load it using csvread


Next, we’ll try read in some .csv data. To read in .csv data we will need to make use of some low-level file access functions. To make things easier, let’s write a function!

Download read_json.m

Now we can download the .csv file. Download json_data.json

And finally we can read the file into Matlab

You’ll notice the data reads into a struct. This allows us to work with both numeric and text (the labels )


Next we’ll load up a .mat file.

Download the following the .mat file and then trying load it. Download trialTable.mat

Once you’ve loaded it, take a look at it in the variable browser.


Finally, try and use the writeStruct2csv to write the trialTable struct to a .csv file. You should then be able to load the .csv file in excel.

Here is the code again, if you need it:

Download writeStruct2csv.m

An easy way to do this from the matlab GUI is to right-click (or ctrl-click on a Mac) and select Open Outside MATLAB

The assessment

In this final section we’ll chat briefly about the assessment.