Lesson 1: Hello World!

In this script we'll learn how to open a 'screen' using the psychtoolbox, put up some text, pause, and close the window. Once you get this working, you're well off the ground for putting up stimuli with the psychtoolbox.

Contents

Opening the screen

Most commands using the psychtoolbox are called using a single matlab function, SCREEN. The first argument for SCREEN is the name of the command, and the rest are arguments specific to that command. Getting help for the Screen command is a bit unconventional. Rather than typing 'help Screen', to get a list of commands, type:

Screen
Usage:

% Activate compatibility mode: Try to behave like the old MacOS-9 Psychtoolbox:
oldEnableFlag=Screen('Preference', 'EmulateOldPTB', [enableFlag]);

% Open or close a window or texture:
[windowPtr,rect]=Screen('OpenWindow',windowPtrOrScreenNumber [,color] [,rect] [,pixelSize] [,numberOfBuffers] [,stereomode] [,multisample][,imagingmode]);
[windowPtr,rect]=Screen('OpenOffscreenWindow',windowPtrOrScreenNumber [,color] [,rect] [,pixelSize] [,specialFlags] [,multiSample]);
textureIndex=Screen('MakeTexture', WindowIndex, imageMatrix [, optimizeForDrawAngle=0] [, specialFlags=0] [, floatprecision=0] [, textureOrientation=0] [, textureShader=0]);
Screen('Close', [windowOrTextureIndex or list of textureIndices/offscreenWindowIndices]);
Screen('CloseAll');

%  Draw lines and solids like QuickDraw and DirectX (OS 9 and Windows):
currentbuffer = Screen('SelectStereoDrawBuffer', windowPtr [, bufferid] [, param1]);
Screen('DrawLine', windowPtr [,color], fromH, fromV, toH, toV [,penWidth]);
Screen('DrawArc',windowPtr,[color],[rect],startAngle,arcAngle)
Screen('FrameArc',windowPtr,[color],[rect],startAngle,arcAngle[,penWidth] [,penHeight] [,penMode])
Screen('FillArc',windowPtr,[color],[rect],startAngle,arcAngle)
Screen('FillRect', windowPtr [,color] [,rect] );
Screen('FrameRect', windowPtr [,color] [,rect] [,penWidth]);
Screen('FillOval', windowPtr [,color] [,rect] [,perfectUpToMaxDiameter]);
Screen('FrameOval', windowPtr [,color] [,rect] [,penWidth] [,penHeight] [,penMode]);
Screen('FramePoly', windowPtr [,color], pointList [,penWidth]);
Screen('FillPoly', windowPtr [,color], pointList [, isConvex]);

% New OpenGL functions for OS X:
Screen('glPoint', windowPtr, color, x, y [,size]);
Screen('gluDisk', windowPtr, color, x, y [,size]);
Screen('DrawDots', windowPtr, xy [,size] [,color] [,center] [,dot_type]);
Screen('DrawLines', windowPtr, xy [,width] [,colors] [,center] [,smooth]);
[sourceFactorOld, destinationFactorOld, colorMaskOld]=Screen('BlendFunction', windowIndex, [sourceFactorNew], [destinationFactorNew], [colorMaskNew]);

% Draw Text in windows
textModes = Screen('TextModes');
oldCopyMode=Screen('TextMode', windowPtr [,textMode]);
oldTextSize=Screen('TextSize', windowPtr [,textSize]);
oldStyle=Screen('TextStyle', windowPtr [,style]);
[oldFontName,oldFontNumber]=Screen(windowPtr,'TextFont' [,fontNameOrNumber]);
[normBoundsRect, offsetBoundsRect]= Screen('TextBounds', windowPtr, text [,x] [,y] [,yPositionIsBaseline] [,swapTextDirection]);
[newX,newY]=Screen('DrawText', windowPtr, text [,x] [,y] [,color] [,backgroundColor] [,yPositionIsBaseline] [,swapTextDirection]);
oldTextColor=Screen('TextColor', windowPtr [,colorVector]);
oldTextBackgroundColor=Screen('TextBackgroundColor', windowPtr [,colorVector]);

% Copy an image, very quickly, between textures, offscreen windows and onscreen windows.
[resident [texidresident]] = Screen('PreloadTextures', windowPtr [, texids]);
Screen('DrawTexture', windowPointer, texturePointer [,sourceRect] [,destinationRect] [,rotationAngle] [, filterMode] [, globalAlpha] [, modulateColor] [, textureShader] [, specialFlags] [, auxParameters]);
Screen('DrawTextures', windowPointer, texturePointer(s) [, sourceRect(s)] [, destinationRect(s)] [, rotationAngle(s)] [, filterMode(s)] [, globalAlpha(s)] [, modulateColor(s)] [, textureShader] [, specialFlags] [, auxParameters]);
Screen('CopyWindow', srcWindowPtr, dstWindowPtr, [srcRect], [dstRect], [copyMode])

% Copy an image, slowly, between matrices and windows :
imageArray=Screen('GetImage', windowPtr [,rect] [,bufferName] [,floatprecision=0] [,nrchannels=3])
Screen('PutImage', windowPtr, imageArray [,rect]);

% Synchronize with the window's screen (on-screen only):
[VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] = Screen('Flip', windowPtr [, when] [, dontclear] [, dontsync] [, multiflip]);
Screen('AsyncFlipBegin', windowPtr [, when] [, dontclear] [, dontsync] [, multiflip]);
[VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] = Screen('AsyncFlipEnd', windowPtr);
[VBLTimestamp StimulusOnsetTime FlipTimestamp Missed Beampos] = Screen('AsyncFlipCheckEnd', windowPtr);
[VBLTimestamp StimulusOnsetTime swapCertainTime] = Screen('WaitUntilAsyncFlipCertain', windowPtr);
[telapsed] = Screen('DrawingFinished', windowPtr [, dontclear] [, sync]);
framesSinceLastWait = Screen('WaitBlanking', windowPtr [, waitFrames]);

% Load color lookup table of the window's screen (on-screen only):
[gammatable, dacbits, reallutsize] = Screen('ReadNormalizedGammaTable', windowPtrOrScreenNumber [, physicalDisplay]);
Screen('LoadNormalizedGammaTable', windowPtrOrScreenNumber, table [, loadOnNextFlip] [, physicalDisplay]);
oldclut = Screen('LoadCLUT', windowPtrOrScreenNumber [, clut] [, startEntry=0] [, bits=8]);

% Get (and set) information about a window or screen:
screenNumbers=Screen('Screens' [, physicalDisplays]);
windowPtrs=Screen('Windows');
kind=Screen(windowPtr, 'WindowKind');
isOffscreen=Screen(windowPtr,'IsOffscreen');
hz=Screen('FrameRate', windowPtrOrScreenNumber [, mode] [, reqFrameRate]);
hz=Screen('NominalFrameRate', windowPtrOrScreenNumber [, mode] [, reqFrameRate]);
[ monitorFlipInterval nrValidSamples stddev ]=Screen('GetFlipInterval', windowPtr [, nrSamples] [, stddev] [, timeout]);
screenNumber=Screen('WindowScreenNumber', windowPtr);
rect=Screen('Rect', windowPtrOrScreenNumber);
pixelSize=Screen('PixelSize', windowPtrOrScreenNumber);
pixelSizes=Screen('PixelSizes', windowPtrOrScreenNumber);
[width, height]=Screen('WindowSize', windowPointerOrScreenNumber);
[width, height]=Screen('DisplaySize', ScreenNumber);
[oldmaximumvalue oldclampcolors] = Screen('ColorRange', windowPtr [, maximumvalue][, clampcolors=1]);
info = Screen('GetWindowInfo', windowPtr [, infoType=0] [, auxArg1]);
resolutions=Screen('Resolutions', screenNumber);
oldResolution=Screen('Resolution', screenNumber [, newwidth] [, newheight] [, newHz] [, newPixelSize] [, specialMode]);

% Get/set details of environment, computer, and video card (i.e. screen):
struct=Screen('Version');
comp=Screen('Computer');
oldBool=Screen('Preference', 'IgnoreCase' [,bool]);
tick0Secs=Screen('Preference', 'Tick0Secs', tick0Secs);
psychTableVersion=Screen('Preference', 'PsychTableVersion');
mexFunctionName=Screen('Preference', 'PsychTableCreator');
proc=Screen('Preference', 'Process');
Screen('Preference','SkipSyncTests', skipTest);
Screen('Preference','VisualDebugLevel', level (valid values between 0 and 5));
Screen('Preference', 'ConserveVRAM', mode (valid values between 0 and 3));
Screen('Preference', 'Enable3DGraphics', [enableFlag]);

% Helper functions.  Don't call these directly, use eponymous wrappers:
[x, y, buttonVector]= Screen('GetMouseHelper', numButtons);
Screen('HideCursorHelper', windowPntr);
Screen('ShowCursorHelper', windowPntr);
Screen('SetMouseHelper', windowPntrOrScreenNumber, x, y);

% Internal testing of Screen
timeList= Screen('GetTimelist');
Screen('ClearTimelist');
Screen('Preference','DebugMakeTexture', enableDebugging);

% Movie and multimedia playback functions:
[ moviePtr [duration] [fps] [width] [height] [count]]=Screen('OpenMovie', windowPtr, moviefile [, async=0] [, preloadSecs=1]);
Screen('CloseMovie', moviePtr);
[ texturePtr [timeindex]]=Screen('GetMovieImage', windowPtr, moviePtr, [waitForImage], [fortimeindex], [specialFlags = 0] [, specialFlags2 = 0]);
[droppedframes] = Screen('PlayMovie', moviePtr, rate, [loop], [soundvolume]);
timeindex = Screen('GetMovieTimeIndex', moviePtr);
[oldtimeindex] = Screen('SetMovieTimeIndex', moviePtr, timeindex [, indexIsFrames=0]);
moviePtr = Screen('CreateMovie', windowPtr, movieFile [, width][, height][, frameRate=30][, movieOptions]);
Screen('FinalizeMovie', moviePtr);
Screen('AddFrameToMovie', windowPtr [,rect] [,bufferName] [,moviePtr=0] [,frameduration=1])

% Video capture functions:
devices = Screen('VideoCaptureDevices' [, engineId]);
videoPtr =Screen('OpenVideoCapture', windowPtr [, deviceIndex] [,roirectangle] [, pixeldepth] [, numbuffers] [, allowfallback] [, targetmoviename] [, recordingflags] [, captureEngineType]);
Screen('CloseVideoCapture', capturePtr);
[fps starttime] = Screen('StartVideoCapture', capturePtr [, captureRateFPS] [, dropframes=0] [, startAt]);
droppedframes = Screen('StopVideoCapture', capturePtr);
[ texturePtr [capturetimestamp] [droppedcount] [summed_intensityOrRawImageMatrix]]=Screen('GetCapturedImage', windowPtr, capturePtr [, waitForImage=1] [,oldTexture] [,specialmode] [,targetmemptr]);
oldvalue = Screen('SetVideoCaptureParameter', capturePtr, 'parameterName' [, value]);

% Low level direct access to OpenGL-API functions:
% Online info for each function available by opening a terminal window
% and typing 'man Functionname' + Enter.

Screen('glPushMatrix', windowPtr);
Screen('glPopMatrix', windowPtr);
Screen('glLoadIdentity', windowPtr);
Screen('glTranslate', windowPtr, tx, ty [, tz]);
Screen('glScale', windowPtr, sx, sy [, sz]);
Screen('glRotate', windowPtr, angle, [rx = 0], [ry = 0] ,[rz = 1]);

% Support for 3D graphics rendering and for interfacing with external OpenGL code:
Screen('Preference', 'Enable3DGraphics', [enableFlag]);  % Enable 3D gfx support.
Screen('BeginOpenGL', windowPtr [, sharecontext]);  % Prepare window for external OpenGL drawing.
Screen('EndOpenGL', windowPtr);  % Finish external OpenGL drawing.
[targetwindow, IsOpenGLRendering] = Screen('GetOpenGLDrawMode');
[textureHandle rect] = Screen('SetOpenGLTextureFromMemPointer', windowPtr, textureHandle, imagePtr, width, height, depth [, upsidedown][, target][, glinternalformat][, gltype][, extdataformat]);
[textureHandle rect] = Screen('SetOpenGLTexture', windowPtr, textureHandle, glTexid, target [, glWidth] [, glHeight] [, glDepth] [, textureShader]);
[ gltexid gltextarget texcoord_u texcoord_v ] =Screen('GetOpenGLTexture', windowPtr, textureHandle [, x][, y]);

% Support for plugins and for builtin high performance image processing pipeline:
[ret1, ret2, ...] = Screen('HookFunction', windowPtr, 'Subcommand', 'HookName', arg1, arg2, ...);
proxyPtr = Screen('OpenProxy', windowPtr [, imagingmode]);
transtexid = Screen('TransformTexture', sourceTexture, transformProxyPtr [, sourceTexture2][, targetTexture][, specialFlags]);

The first Screen command will be 'OpenWindow', the first in the list. To see more about how to use that command, use the Screen command like this.

Screen('OpenWindow?')
Usage:

[windowPtr,rect]=Screen('OpenWindow',windowPtrOrScreenNumber [,color] [,rect][,pixelSize][,numberOfBuffers][,stereomode][,multisample][,imagingmode][,specialFlags]);

Open an onscreen window. Specify a screen by a windowPtr or a screenNumber (0 is
the main screen, with menu bar). "color" is the clut index (scalar or [r g b]
triplet) that you want to poke into each pixel; default is white. If supplied,
"rect" must contain at least one pixel. If a windowPtr is supplied then "rect"
is in the window's coordinates (origin at upper left), and defaults to the whole
window. If a screenNumber is supplied then "rect" is in screen coordinates
(origin at upper left), and defaults to the whole screen. (In all cases,
subsequent references to this new window will use its coordinates: origin at its
upper left.). Please note that while providing a "rect" parameter to open a
normal window instead of a fullscreen window is convenient for debugging, but
drawing performance, stimulus onset timing and onset timestamping may be
impaired, so be careful.
"pixelSize" sets the depth (in bits) of each pixel; default is to leave depth
unchanged. "numberOfBuffers" is the number of buffers to use. Setting anything
else than 2 will be useful for development/debugging of PTB itself but will mess
up any real experiment. "stereomode" Type of stereo display algorithm to use: 0
(default) means: Monoscopic viewing. 1 means: Stereo output via OpenGL on any
stereo hardware that is supported by MacOS-X, e.g., the shutter glasses from
CrystalView. 2 means: Left view compressed into top half, right view into bottom
half. 3 means left view compressed into bottom half, right view compressed into
top half. 4 and 5 allow split screen display where left view is shown in left
half, right view is shown in right half or the display. A value of 5 does the
opposite (cross-fusion). Values of 6,7,8 and 9 enable Anaglyph stereo rendering
of types left=Red, right=Green, vice versa and left=Red, right=Blue and vice
versa. A value of 10 enables multi-window stereo: Open one window for left eye
view, one for right eye view, treat both of them as one single stereo window.
See StereoDemo.m for examples of usage of the different stereo modes. See
ImagingStereoDemo.m for more advanced usage on modern hardware.
"multisample" This parameter, if provided and set to a value greater than zero,
enables automatic hardware anti-aliasing of the display: For each pixel,
'multisample' color samples are computed and combined into a single output pixel
color. Higher numbers provide better quality but consume more video memory and
lead to a reduction in framerate due to the higher computational demand. The
maximum number of samples is hardware dependent. Psychtoolbox will silently
clamp the number to the maximum supported by your hardware if you ask for too
much. On very old hardware, the value will be ignored. Read 'help AntiAliasing'
for more in-depth information about multi-sampling. "imagingmode" This optional
parameter enables PTB's internal image processing pipeline. The pipeline is off
by default. Read 'help PsychGLImageprocessing' for information about this
feature.
Opening or closing a window takes about one to three seconds, depending on type
of connected display. COMPATIBILITY TO OS-9 PTB: If you absolutely need to run
old code for the old MacOS-9 or Windows Psychtoolbox, you can switch into a
compatibility mode by adding the command Screen('Preference', 'EmulateOldPTB',
1) at the very top of your script. This will restore Offscreen windows and
WaitBlanking functionality, but at the same time disable most of the new
features of the OpenGL Psychtoolbox. Please do not write new experiment code in
the old style! Emulation mode is pretty new and may contain significant bugs, so
use with great caution!

See also: OpenOffscreenWindow, SelectStereoDrawBuffer

Yes, that's a lot of verbage! The most important part of this verbage is the first line which describes how to use the command:

[windowPtr,rect]=Screen('OpenWindow',windowPtrOrScreenNumber [,color]
[,rect][,pixelSize][,numberOfBuffers][,stereomode][,multisample][,imagin
gm ode]);

Arguments in [brackets] are optional.

The second Screen command is 'CloseAll'. We'll use 'OpenWindow' and 'Close' together because if we just use 'OpenWindow' alone it'll leave the computer in a state where we can't see the Matlab command window.

Here's a simple set of commands that opens the screen and then closes it. Be sure to run these two lines together:

windowPtr=Screen('OpenWindow',0);
Screen('CloseAll');
PTB-WARNING: Couldn't even collect one single valid flip interval sample! Sanity range checks failed!
PTB-WARNING: Could be a system bug, or a temporary timing problem. Retrying the procedure might help if
PTB-WARNING: the latter is the culprit.
PTB-WARNING: Couldn't even collect one single valid flip interval sample! Sanity range checks failed!
PTB-WARNING: Could be a system bug, or a temporary timing problem. Retrying the procedure might help if
PTB-WARNING: the latter is the culprit.
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!

The second argument '0' means open the default screen on your computer. If you have an external monitor (or projector), you can use '1'.

We can put up text in our screen with the Screen function 'DrawText'. These four lines open the screen, put up some text, pauses for two seconds and closes it:

windowPtr=Screen('OpenWindow',0);
Screen('DrawText',windowPtr,'Hello World!',500,500);
Screen('Flip',windowPtr);
pause(2)
Screen('CloseAll');
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!
PTB-WARNING: Couldn't even collect one single valid flip interval sample! Sanity range checks failed!
PTB-WARNING: Could be a system bug, or a temporary timing problem. Retrying the procedure might help if
PTB-WARNING: the latter is the culprit.
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!

The variable 'windowPtr' returned by 'Screen' when you open the window is important - it holds a pointer to the memory register for the window which needs to be passed back into 'Screen' every time you use it.

What is this 'Flip' command? This is an important Screen function that waits for a signal that the monitor has refreshed before showing everything that has been shown since the previous 'Flip' command. (Actually it's performing a technique called 'double buffering' which involves flipping between two 'display surfaces', but we don't need to go into that right now.)

'Flip' serves two useful functions. First it ensures that any drawing happens after the screen refresh to avoid 'tearing' artifacts that occur when a refresh occurs in the middle of putting up graphics. Second, it gives you control over the timing of your animations. As long as all of your drawing occurs in less than it a single frame (usually something like 1/60 of a second), then your animation will be performed at exactly the frame rate of the monitor, which is a very reliable thing.

Try and Catch

It can be inconvenient if you have a bug in your program that causes the program to terminate when the screen is open. To get out of this you have to switch to the command window by going to the task manager, switching to the matlab command window and typing (blindly) "Screen('CloseAll')". A nice way around this by using the 'try' and 'catch' commands (Thanks to Sungjun Joo for this suggestion). 'try' and 'catch' are commands that allow control over how errors are handled in Matlab. Here's an example:

try
    windowPtr = Screen('OpenWindow', 0);
    %Place a bad line of code here...
catch ME
    Screen('CloseAll');
    rethrow(ME);
end
Screen('CloseAll');
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!
PTB-WARNING: Couldn't even collect one single valid flip interval sample! Sanity range checks failed!
PTB-WARNING: Could be a system bug, or a temporary timing problem. Retrying the procedure might help if
PTB-WARNING: the latter is the culprit.
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!

This should function normally, but if you add a bad line of code anywhere between 'try' and me', control will be sent to the lines following the 'catch' command. Here, the screen is closes and the error message is displayed in the command window using the 'rethrow' command.

A customized version of OpenWindow

You may get a series of scary warnings both in the command window and on the screen when Screen is used, depending on the computer you're using. When a screen is opened, a variety of checks are made by Screen to determine issues such as the timing of the refresh rate. Don't let the guys who wrote the psychtoolbox know I said this, but I find some of these dire warnings to be not so dire, like the ones about skipping video frames. Fortunately, you can turn these warnings off using the 'Screen('Preference') command.

You can set a variety of screen attributes with the 'Screen('Preference') command. You can get help the usual way:

Screen('Preference?')
Usage:

oldPreferenceValue = Screen('Preference', preferenceName, [newPreferenceValue])

Get or set a Psychtoolbox preference.Preference settings are global - they
affect all operations of a module until changed.
oldBool = Screen('Preference', 'IgnoreCase', [psych_bool]);
tick0Secs = Screen('Preference', 'Tick0Secs', tick0Secs);
psychTableVersion = Screen('Preference', 'PsychTableVersion');
mexFunctionName = Screen('Preference', 'PsychTableCreator');
proc = Screen('Preference', 'Process', signature);
proc = Screen('Preference', 'DebugMakeTexture', enableDebugging);
oldEnableFlag = Screen('Preference', 'TextAlphaBlending', [enableFlag]);
oldSize = Screen('Preference', 'DefaultFontSize', [fontSize]);
oldStyleFlag = Screen('Preference', 'DefaultFontStyle', [styleFlag]);
oldfontName = Screen('Preference', 'DefaultFontName', [fontName]);
oldEnableFlag = Screen('Preference', 'DefaultTextYPositionIsBaseline',
[enableFlag]);
oldEnableFlag = Screen('Preference', 'TextAntiAliasing', [enableFlag=-1 (System
setting), 0 = Disable, 1 = Enable, 2 = EnableHighQuality]);
oldEnableFlag = Screen('Preference', 'TextRenderer', [enableFlag=0 (Default
OS-specific [fast]), 1 = HighQ OS-specific]);
oldLocaleNameString = Screen('Preference', 'TextEncodingLocale',
[newLocalenNameString]);
oldEnableFlag = Screen('Preference', 'SkipSyncTests', [enableFlag]);
[maxStddev, minSamples, maxDeviation, maxDuration] = Screen('Preference',
'SyncTestSettings' [, maxStddev=0.001 secs][, minSamples=50][,
maxDeviation=0.1][, maxDuration=5 secs]);
oldEnableFlag = Screen('Preference', 'FrameRectCorrection', [enableFlag=1]);
oldLevel = Screen('Preference', 'VisualDebugLevel', level);

Workaround flags to work around all kind of deficient drivers and hardware:
See 'help ConserveVRAMSettings' for settings and their effect.

oldMode = Screen('Preference', 'ConserveVRAM', mode);

Activate compatibility mode: Try to behave like the old MacOS-9 Psychtoolbox:
oldEnableFlag = Screen('Preference', 'EmulateOldPTB', [enableFlag]);

oldEnableFlags = Screen('Preference', 'Enable3DGraphics', [enableFlags]);
oldEnableFlag = Screen('Preference', 'SuppressAllWarnings', [enableFlag]);
oldMode = Screen('Preference', 'VBLTimestampingMode', [newmode]);
oldVTOTAL = Screen('Preference', 'VBLEndlineOverride' [, newVTOTAL]);
oldMode = Screen('Preference', 'DefaultVideocaptureEngine', [newmode
(0=Quicktime-SequenceGrabbers, 1=LibDC1394-Firewire, 2=LibARVideo)]);
oldMode = Screen('Preference', 'OverrideMultimediaEngine', [newmode (0=System
default, 1=GStreamer)]);
oldLevel = Screen('Preference', 'WindowShieldingLevel', [newLevel (0 = Behind
all other windows - 2000 = In front of all other windows, the default)]);
residuals = Screen('Preference', 'SynchronizeDisplays', syncMethod);
oldLevel = Screen('Preference', 'Verbosity' [,level]);

See also: 

I've written a function called 'OpenWindow' that calls 'OpenScreen' after setting some of the preferences beforehand to avoid warnings (if desired). I find this function useful because it hides a bunch of ugly lines that I used to have to include every time I opened the window. It also opens the screen to a default color of black.

It also introduces a structure called 'display' that contains useful information about the current computer display, such as the 'windowPtr' variable. Later we'll add fields to this structure about the viewing distance that will allow us to define our stimuli in 'real-world' parameters like degrees of visual angle and seconds rather than display-oriented parameters like pixels and frames.

Here's an example of how to use 'OpenWindow'.

try
    display.skipChecks =1;
    display.bkColor = [255,255,255];
    display = OpenWindow(display);
    Screen(display.windowPtr,'DrawText','Psychophysics Rules!',500,500,[255,0,0]);
    Screen('Flip',display.windowPtr);
    pause(2)
catch ME
    Screen('CloseAll');
    rethrow(ME)
end
Screen('CloseAll');
PTB-WARNING: Couldn't even collect one single valid flip interval sample! Sanity range checks failed!
PTB-WARNING: Could be a system bug, or a temporary timing problem. Retrying the procedure might help if
PTB-WARNING: the latter is the culprit.
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!
PTB-WARNING: Couldn't even collect one single valid flip interval sample! Sanity range checks failed!
PTB-WARNING: Could be a system bug, or a temporary timing problem. Retrying the procedure might help if
PTB-WARNING: the latter is the culprit.
PTB-WARNING: Couldn't collect valid flip interval samples! Fatal VBL sync failure!
PTB-WARNING: Either synchronization of doublebuffer swapping to the vertical retrace signal of your display is broken,
PTB-WARNING: or the mechanism for detection of swap completion is broken. In any case, this is an operating system or gfx-driver bug!

Note the [255,0,0] which defines the color of the text to be red (r,g,b).

Also check out the display structure:

display
display = 

    skipChecks: 1
       bkColor: [255 255 255]
     screenNum: 0
     windowPtr: 10
     frameRate: 60.0553
    resolution: [2048 768]
        center: [1024 384]

(Your results may vary). It has fields with information about the display's frame rate and screen resolution.

You can set some parameters for OpenWindow by passing in an existing 'display' structure. More information about this can be seen by getting help:

help OpenWindow
 display = OpenWindow([display])
 
 Calls the psychtoolbox command "Screen('OpenWindow') using the 'display'
 structure convention.
 
 Inputs:
    display             A structure containing display information with fields:
        screenNum       Screen Number (default is 0)
        bkColor         Background color (default is black: [0,0,0])
        skipChecks      Flag for skpping screen synchronization (default is 0, or don't check)
                        When set to 1, vbl sync check will be skipped,
                        along with the text and annoying visual (!) warning
 
 Outputs:
    display             Same structure, but with additional fields filled in:
        windowPtr       Pointer to window, as returned by 'Screen'
        frameRate       Frame rate in Hz, as determined by Screen('GetFlipInterval')
        resolution      [width,height] of screen in pixels
        center          [x,y] center of screeen in pixels 
 
 Note: for full functionality, the additional fields of 'display' should be
 filled in:
 
        dist             distance of viewer from screen (cm)
        width            width of screen (cm)

Exercises

For this week's exercises, please use the 'try' and 'catch' commands as described here, and use the OpenWindow function.

  1. Write a script called 'YellowOnBlue.m' that opens the screen with a blue background, puts up yellow letters [255,255,0] saying 'Yellow on Blue', pauses for 5 seconds and closes the window.
  2. Use the 'Flip' command in a loop instead of the 'Pause' command. For example, if your monitor has a frame rate of 60Hz, then a loop with 60 calls to 'Flip' will take exactly one second.