The aim of these demos is to provide an introduction to how to program using Psychtoolbox (PTB). To get started you will need to have installed Matlab or Octave (a free version of Matlab) and followed the install instructions which are provided here on the PTB website (please read the instructions before installing, most errors are due to simply not reading the installation instructions). If you have previously installed PTB I recommend you use the "UpdatePsychtoolbox" command to get the latest version.
Note: If you want PTB to work fully with Matlab, you will need to use R2015aSP1 or earlier. PTB doesn't work fully with versions beyond this due to incompatibilities.
There are around 40 demos on this site and these are organised into sections based on learning different aspects of PTB. For all users I strongly suggest looking at sections (1) and (2) as these show essential features which will help get you up to speed coding in Matlab and PTB. If you are not clear on the essentials, you will struggle with anything more difficult.
Please make sure you carefully read the comments in the code as these provide an explanation of why things are done the way they are. Please also look at a range of demos, don't just read one or two, ignoring the rest, and assume you know everything there is to know. This will result in confusion.
The demos provided as an educational resource. I provide absolutely no guarantees that the demos provide "best practice" for your specific needs.
Please contact me if you (1) find any bugs or errors, (2) would like to donate demo's, or (3) can point out areas for improvement.
Do not contact me if you want me to write your code for you.
PTB has an active forum which can be found here. If you have problems with core PTB functionality ask questions there. It essential you provide full and sufficient information when posting on the forum, see guidelines here. PTB is now primary developed for Linux, reduced functionality and support is provided for Windows and OSX, so one would need to bear this in mind when interpreting any response.
Note for Octave users only: Octave does not support the "clearvars" function used at the start of each of my demo scripts (I do not use Octave). The demos will be functional after replacing "clearvars" with "clear". With that change things should run just fine.
Final note: Believe it or not programming can be a lot of fun. Don't get disheartened if you have difficulties. Learning something cool is rarely super easy, that's the whole point.
(1) The bsics
Totally Minimal Demo: This demo aims to be as minimal as possible. It opens a screen and colours it grey. Thats it. But it demonstrates pretty much the steps you will always use when starting a program i.e. opening a on-screen window.
Totally Minimal Demo #2: This is the same as "TotallyMinimalDemo", except after opening the window we query numerous things about it. This demos how to get pretty much all the basic info you will need about the screen.
Accurate Timing Demo: This demo shows three basic ways in which to present a stimulus which would change on each frame. I demonstrate varying degrees of potential accuracy. Please read the extensive comments in the demo closely, they are important and should not be ignored. For presenting a stimulus which is unchanging, or changes less frequently then each frame, see the next demo.
Wait Frames Demo: Here we demonstrate how to update an image on the screen at a rate different to that of the monitors refresh rate. For example, you might want to update the stimulus every second, rather then at the frame rate of your monitor.
NOTE: For the purposes of subsequent demos we rarely specify timing precisely. This is for demo purposes only, so as to ensure that the demos will run on systems not capable of precise timing. When presenting visual stimuli in a real experiment you should use accurate timing. Overall timing on systems can vary greatly, both between different systems, and with different tasks on the same system. If timing is important to you then take the time to measure it. Don’t leave things to chance.
Screen Coordinates Demo: In this demo you can move the mouse cursor around the screen and we write text on the screen letting you know what the X and Y pixel coordinates of the cursor are (rounded to the nearest pixel). This allows you to picture how screen coordinates are defined as well as how to query the position of the mouse.
(2) Drawing basic shapes and dots
This set of demos will show you how to draw static shapes, lines and dots. Much of the code in these demos shows the core functionality of drawing to the screen with PTB so will be a valuable start-point for understanding the material covered in latter demos.
Single Dot Demo: This very simple demo draws a single dot on the screen in a randomly determined position.
Dot Grid Demo: Shows you how to draw multiple dots with different properties in a single line of code. In this example a uniform grid of dots with different positions, sizes and colours.
Square Demo: Shows you how to draw a rectangle and position it on the screen. See also "Rectangle Coordinates Demo" which interactively shows how screen rectangles are defined by their coordinates.
Multiple Squares Demo: Shows you how to draw multiple rectangles with different colours simultaneously.
Different Squares Demo: Shows you how to draw multiple rectangles each differing in both size and colour.
Framed Squares Demo: Shows you how to draw multiple framed squares simultaneously.
Oval Demo: Shows you how to draw an oval (see also the smoothed anti-aliased version).
Polygon Demo: Shows you how to draw a polygon with an arbitrary number of sides (see also the smoother anti-aliased version).
Framed Polygon Demo: Shows you how to draw an outline of a polygon with lines (rather then filled).
Fixation Cross Demo: Illustrates how to draw multiple lines to make a fixation cross.
Checker-Board Demo: Builds on previous demos by showing how to build a multi-coloured and a black-and-white checker-board.
Order Of Drawing Demo: This demo explains about sequential drawing. This is key to drawing multiple objects to the screen e.g. overlapping objects.
Simultaneous Contrast Illusion Demo: This demo builds on "Order Of Drawing Demo" by drawing a simple simultaneous contrast illusion, this time with all the objects draw in a single line of code.
Semi-Transparent Squares Demo: Shows you how to make shapes semi-transparent using the "alpha" channel, so that you can partially "see through shapes" to those behind. Again, the order of operations is key.
(3) Animating basic shapes and dots
Now we have mastered drawing static stimuli to the screen, we will learn how to animate these shapes. Essentially this will allow us to translate, rotate expand and shrink objects drawn to the screen. We will also learn how to change the colour and size of objects contingent upon their movement. And finally, also learn how to interact with objects on the screen with the mouse or keyboard.
Moving Dot Grid Demo: Builds on "Dot Grid Demo" by animating the dot grid moving sinusoidally left and right across the screen.
Scaled Dot Grid Demo: Shows you how to expand and contract a grid of dots draw on the screen. The size of the dots also modulates contingent upon their expansion.
Moving Square Demo: Shows how to animate a square moving sinusoidally left and right across the screen.
Multiple Moving Squares Demo: Shows how to animate two squares moving sinusoidally across the screen with different colours and different lateral offsets.
Moving Colour Change Square Demo: Animates a square moving sinusoidally across the screen, with its colour being dynamically contingent on its screen position.
Moving Size Change Square Demo: Animates a square moving sinusoidally across the screen, with its size being contingent on its screen position.
Rotating Squares Demo: Animates three different coloured rotating squares using basic OpenGL commands.
Mouse In Square Demo: Shows how change the colour of a square contingent upon whether or not the mouse cursor is inside it or not.
Keyboard Contingent Square Demo: Shows how the position of a square can be interactively moved around the screen buy pressing keys on the keyboard (in this case the arrow keys).
Rectangle Coordinates Demo: This demo builds on "Screen Coordinates Demo" and "Square Demo" by showing you how a screen rectangle is defined by its top-left and bottom-right coordinates. Move the rectangle around the screen with the keyboard and see how the coordinates change. Also shown for information is the central coordinates of the rectangle.
Mouse Contingent Square Demo: Shows how the position of a square can be yoked to the position of the mouse.
(4) Static textures
We now move on to textures. You can imagine a "texture" as simply a picture i.e. a pattern of pixel values showing anything at all. Textures can be pictures loaded in from file e.g. a picture of a face, or those created in Matlab and/or PTB e.g. a grating. In this section we will introduce all you will need to get a basic understanding of drawing static textures to the screen. This will include scaling and rotating textures upon drawing to any region of the screen.
Show Image Demo: Shows you how to load an image into PTB and then present it on the screen for a specific amount of time. Specifically, the code presents an image for two seconds on a grey background, fills the screen green for two seconds, then finally presents the same image (now upside down) again for two seconds, this time on the green background.
Gabor Demo: This demo shows you how to draw a standard Gabor using PTB's procedural texture support. This allow one to draw many Gabors patches in an extremely efficient manner. For this demo we simply draw one Gabor in the center of the screen. There are a few specific parameters that need to be set to draw a standard Gabor. This demo shows you how to do that.
Spiral Texture Demo: Shows you how to define a texture in PTB, in this case a spiral. Then draw it to multiple positions on the screen simultaneously, whilst also modulating each drawn textures colour.
Pinwheel Texture Demo: Same as Spiral Texture Demo, except this time with pinwheel textures.
Scaled Spiral Texture Demo: Shows how you can dynamically rescale a single texture to be different sizes when drawn to the screen.
Scaled Image Demo: Shows you how to load an image into PTB then dynamically rescale it multiple times when drawing it to the screen. This builds on what you have learned in "Show Image Demo" and "Scaled Spiral Texture Demo".
Checkerboard Texture Demo: Exploits dynamic texture scaling to draw a checkerboard texture very efficiently. The original 4 x 4 pixel texture is scaled up by 90%. Also demonstrates how to rotate textures when drawing them to the screen (see the animated texture demos for more information on texture rotation).
Contrast Modulated Spiral Demo: Here we create a set of three, coloured, contrast-modulated spiral textures. We do this buy contrast modulating a noise background with a spiral texture mask. This mask is draw into the 'alpha' channel of the spiral texture.
Radial Checkerboard Demo: Displays an animated radial checkerboard, as is typically used for visual field mapping in fMRI (this demo is a modified version of one coded by Keith Schneider).
Bubble Aperture Demo: This demo shows how to produce a basic "Bubbles" stimulus. We load the standard PTB "bunnies" image into a texture and then view it through a mask consisting of an opaque grey layer punctuated by Gaussian apertures through which the bunnies image can be seen. You can easily explore all the components of the stimulus e.g. try drawing only the original Gaussian mask over the image.
(5) Animated textures
We will now focus on animating textures. This will include rotating textures, both internally and externally. As well as using translating textures to construct drifting stimuli such as gratings and Gabors. We will also look at a more complex stimulus, which involves drawing multiple drifting Gabor stimuli simultaneously. This will build on your knowledge of alpha blending gained from previous demos. Also, PTB provides a excellent range of demos showing this type of functionality. These are referenced and linked below.
Rotating Checkerboard Demo: In this demo we make a single 4 x 4 pixel checkerboard texture and draw it to the screen simultaneously in four separate positions. Each checkerboard is colour modulated, rescaled by 50x and rotated. This drawing can all be accomplished in a single line of code.
Internal External Texture Rotation Demo: In this demo we demonstrate the difference between "external" and "internal" texture rotation. A pinwheel texture is drawn to the screen in four positions, each colour modulated. The left two textures rotate "externally" the right two textures "internally".
Rotating Contrast Modulated Spiral Demo: In this demo we animate the alpha layer of three contrast-modulated spiral textures, to produced coloured contrast modulated rotating spirals.
Contrast Modulated Grating Demo: This is a modified version of "DriftDemo2" included with PTB. I've modified it to draw a contrast modulated grating (second order grating) rather then a luminance modulated grating (first order grating).
Global Motion Gabor Array: This demo draws an array of drifting Gabors using procedural textures. The Gabors have randomly assigned orientations and their drift speed is assigned to be consistent with a single "2D" velocity. For details click here for the original paper introducing the stimulus. Also, see my own publications for some work which has used this type of stimulus.
Windowed Radial Checkerboard Demo: Displays an animated radial checkerboard viewed through a mask which allows you to display segments of the checkerboard pattern (this demo is a modified version of one coded by Keith Schneider).
Moving Windowed Radial Checkerboard Demo: Same as Windowed Radial Checkerboard Demo except now the checkerboard mask rotates (this demo is a modified version of one coded by Keith Schneider). Note: you might perceive the mask to occasionally “jump” so that the motion no longer appears smooth, this is an illusion caused by the contrast reversal.
Fading Texture Demo: This demo loads a picture of rabbits included in the PTB distribution, and dynamically fades the texture in and out of visibility with a temporal sine wave function. It does this by changing the "alpha" value of the texture (this is called alpha blending, or compositing). The alpha value ranges between 0-1, 0 being completely invisible and 1 being completely visible. For a value of 0.5 you can see half of the image and half of the background colour (the alpha value of the texture oscillates around this value during the demo).
This set of demos will show you the basics of how to draw text, position it on the screen and move it dynamically. We cover how to stereoscopically present text so that it is in a different depth plane to the screen in later demos. For these demos we will be using PTB's "DrawFormattedText" command, as this provides an versatile and straightforward to draw formatted text.
Basic Text Demo: This is a basic as it gets. Simply writes “Hello World” at three different screen positions, in three different colours, in three different fonts.
New Line Text Demo: In this demo we show you how to draw write multiple lines of text in a single go, how to concatenate lines of text and how to place line breaks in text.
Mirror Text Demo: Shows you how to draw mirror reversed text. This is useful if you are presenting text on a monitor viewed via a mirror e.g. when viewing a monitor in a mirror stereoscope. The text is the same as in "Basic Text Demo, but now the top line is flipped horizontally, the middle line is flipped vertically, and bottom line is flipped both horizontally ad vertically i.e. shown upside down.
Countdown Timer Demo: This demo shows how to implement a simple countdown timer. The timer starts at 10 and counts down to 0, with the number shown on the screen updating each second. The color of the text updates randomly each time the number changes. The demo is set up to show you how to update the screen with text contingent upon the frame number. More complex demos are also possible e.g. fractional seconds. This one is aimed just to get you started.
Moving Text Demo: In this demo we show you how to animate text. We write "Hello World" in different vertical positions on the screen and then oscillate the horizontal position of the text sinusoidally over time. The animation loop is just the same as in Multiple Moving Squares Demo. Except this time with are animating the position of text.
Rotating Text Demo: In this demo we show you dynamically rotate text. PTB doesn't offer a direct way in which to rotate text using the "DrawFormattedText" command, however it is very simple to rotate the text ourselves. We do this by drawing the text to a texture. Then drawing the texture to the screen. You can essentially treat textures like windows, as they are in some ways equivalent.
These demos will show you the basics of getting Psychtoolbox to produce sounds for you. We will first looks at producing sounds without any accompanying visuals, and then at synchronising sound with visuals. All of these demos will use PsychPortAudio as this offers the most robust and versatile way to present sounds in Psychtoolbox.
Note: These demos produce sounds. I have use volume settings in code which produce comfortable sounds on my system, but this might not be the case for yours. Please make sure you turn your volume to a very low level before playing the demos for the first time so as to check the volume.
Simple Beep Demo: In this demo we simply make play a beep for one second, pause for a second, and then play another beep for a second. That’s it. However, this shows you how to setup PsychPortAudio for sound playback. You will use very similar syntax for many forms of sound playback.
Beep Text Demo: In this demo build on Simple Beep Demo by concurrently presenting visual stimui at the same time as the beeps. The screen will show "BEEP" for the duration of the beeps and "SILENCE" when a beep is not playing.
(8) 3D stimuli without stereoscopic presentation
We will now move on to drawing 3D stimuli. In this section we will use cues such as motion, perspective and shading to define our 3D objects. This means that no special equipment is used to display the images.
Structure From Motion Demo: Shows how to render a 3D rotating cylinder with moving dots. Structure from motion, in this instance, is ambiguous about the depth of the cylinder, as the dots are projected orthographically onto a 2D surface (your screen). The stimulus will therefore be perceived to ‘flip’ rotation direction. In fact, the stimulus is quad-stable i.e. there are four possible stable interpretations of its depth structure.
Cubes Demo: This simple demo will introduce you to 3D rendering with OpenGL. OpenGL is a powerful way in which to create stimuli and is at the heart of much of PTB, all be it behind the scenes. This demo renders an array of 3D cubes, each with a different position and rotation angle. It lights these cubes with a single light source. The scene is rendered with anti-aliasing via multi-sampling to give us nice smooth edges.
Rotating Cubes Demo: This demo builds directly on Cubes Demo by rendering the cubes randomly rotating.
Rotating Light Source Demo: In this demo we render a light source rotating around a sphere. The user will be able to see how the changing light-source position effects the luminance of the spheres surface. We also introduce the concept of “display lists”, which can be used to speed up rendering.
(9) 3D stimuli with stereoscopic presentation
In the following demos you will learn how to render stereoscopic stimuli. We first start with simple demos which require no knowledge of OpenGL. We will then move onto demos which utilise OpenGL to do geometrically correct perspective projection. All demos will be set to render stereo using red-green anaglyph images, but can be switch to alternative methods by changing a single number. Note: You may experience some “ghosting” of the left and right eyes images, this is to be expected if your monitor is not calibrated to the anaglyph filters you are using and the displayed images.
Square In Depth Demo: This demo introduces stereoscopic presentation by rendering a random dot stereogram of a square positioned in a depth plane in front of the screen. In this simple demo we achieve this by shifting the position of dots in the left and right eyes in equal and opposite directions on the computer screen. This is not necessarily geometrically correct, but a good start for learning about rendering stereoscopic stimuli as you have direct access to the dot coordinates on each frame.
Square Moving in Depth Demo: This demo extends Square in Depth Demo by using an animation loop to render the square oscillating in depth about the plane of the monitor screen.
Slanted Surface Demo: This demo renders a random dot stereogram of a slanted surface. For this simple demo, this is achieved by laterally magnifying the positions of one eyes dots on the computer screen. Together with the first two stereo demos this demonstrates how stereoscopic presentation is achieved by presenting different images to the two eyes. But again, this is not geometrically correct (i.e. not true perspective projection).
Modulating Slant Demo: This demo extends Slanted Surface Demo by using an animation loop to render a 3D surface dynamically changing in slant over time.
(10) Full Experiments
In this section we will use the full knowledge we have gained to code some simple experiments. This will allow you to see how to construct an experimental script and how to use standard psychophysical techniques such as the method of constant stimuli.
Stroop Task Demo: This page will talk you through designing a simple experiment with Psychtoolbox. We will use a standard example: the Stroop Task. Code will be provided and you will hopefully learn about how to structure a piece of experimental code.
Orientation Threshold Demo: This demo will show you how to get an orientation threshold using a two alternative forced choice experiment, with the method of constant stimuli.
Change Blindness Demo: This demo shows you a basic change blindness experiment where two pictures alternate with one another, separated by a blank screen. Either an object in the image changes colour, or disappears and reappears. Press the space bar when you see the change. The length of time it has taken you to see the change is recorded. The code file needs to be placed in the same directory as the folder of images, which can be downloaded here. This demo is a modified version of one by Krista Ehinger.
(11) Contributed Code
In this section I provide demos of code which has been contributed to the site. This can be either pure PTB code or code that can be used in cool ways in conjunction with PTB. All of the contributed code is free to use and modify, just as with all the other demos. In some cases, if you use the code in your own work, you should cite the academic papers on which the contributed code is based. If this is the case, it will be clearly stated in the code which has been contributed.
Log Gabor Filter Demo: This demo uses code contributed by Prof. Steven Dakin (University of Auckland) which implements a Log-Gabor filter (click here to download the file). The demo I've made uses Steven's code to filter a face image included in the PTB distribution. Various filter parameters are used and the original image and filtered images are displayed on the screen. The code cycles through various filtered images and displays the parameters of the filter used at the bottom of the screen. Full details of how the filter works, and the paper to cite if you use the technique, are provide in Steven's code.