####Matlab Programming Notes####
An Introduction to Matlab
Help for Psychtoolbox
- For beginners: Psychtoolbox Tutorial and Ione Fine's Psychtoolbox Tutorial.
- The Psychtoolbox includes built-in help available from the MATLAB command line.
- Enter "help Psychtoolbox" at the MATLAB prompt for a list of Psychtoolbox function categories.
- To display a list of Psychtoolbox functions within a category ask for help with the category, e.g. "help PsychBasic."
- To get help for a Psychtoolbox function ask for help on the function, e.g. "help GetChar."
- Psychtoolbox functions such as Screen,which accept a subcommand as an argument, include built-in help for there subcommands.
- For a list of all subcommands issue the function call with no arguments, e.g. enter "Screen" at the command line.
- To display documentation for a subcommand invoke the subcommand with a trailing question mark, e.g. Screen('OpenWindow?')
- For a list of all subcommands issue the function call with no arguments, e.g. enter "Screen" at the command line.
- Enter "help Psychtoolbox" at the MATLAB prompt for a list of Psychtoolbox function categories.
- Read our answers to frequently asked questions.
- Your friends and colleagues might help. Check out the Psychtoolbox forum.
Help for MATLAB
- Typing "doc" in MATLAB will activate their browser-based help system, which is quite handy.
- You can search the Mathworks web site.
- There's an active MATLAB newsgroup (mostly Windows and unix users).
- Typing "help" and "help help" at the MATLAB command line will list help topics and explain MATLAB help.
3. CRT Monitors and VGA:
–High-level language •slow to interpret by machine •easy to understand by humans
MATLAB is optimized for matrix-based calculations
•lookfor string
Second dimension = number of columns
>> e=['world','hello']
e =
worldhello
>> e=['world';'hello']
e =
hello
u(n) = u(n-1) x (n+1)
with u(1) = 1
function
[u]=u(n)
u(1)=1;
for
i=2:n
u(i)=u(i-1)*(i+1);
end
---solution 2:uofi.m----
u=zeros(10,1);
u(1)=1;
for
n=2:10
u(n,1)=u(n-1,1).*(n+1);
end
u
It would be even nicer, if we asked the user the first value of the series. –
–Use ‘input’ – –Syntax:
VAR = input(‘your text here’); – (EVALUATED INPUT)
–For entering strings of characters
VAR = input(‘Your text here’,’s’); – (NOT EVALUATED INPUT)
SWITCH:
syntax
•More generally, if testing the value inside variable 'n'
•switch n
• case n1
• …
• case n2
• …
• otherwise
• …
•end
type 'q'
%Write a program that asks user for PIN number, until user gets it right.
correctPin = 1234;
true =1;
counter=0;
while true
guessPin=input('Please input your PIN,type q to quit:\n')
counter=counter+1;
if guessPin==correctPin
disp('you input the correct PIN\n')
break;
elseif guessPin=='q'
disp('you quited successfully\n')
break;
else
disp('you input the wrong PIN\n')
end
if counter==3
disp('you failed for three times!\n')
break
end
end
find
–FINDS a specific value in an array (or matrix) and returns the
–SYNTAX:
indeces = find(expression);
–returns indeces for which expression is true.
Functions
•- can take input (passing variables)
•- can return outputs.
-variables are internal.
-NAME OF M-FILE AND FUNCTION HAVE TO BE THE SAME.
------example of function:-----------
Persistent Variables
•If you want a function to keep accessing a variable, every time you run it, declare the variable as persistent.
GLOBAL variables:
• -> can be used ANYWHERE…
• modified anywhere too!
•
•PERSISTENT variables:
• -> allow you to have some values persist in memory from one function use to the next.
• -> UNTOUCHABLES!! outside of function.
•
• -> beware of what's lurking under the surface.
For further reading…
•> anonymous functions (do not require an m-file)
• > f = @(arglist)expression
• > sqr = @(x) x.^2;
•> subfunctions are created within a function
•> private functions: only visible to their parent directory scripts.
•> nested functions: share variables.
SAVING AND READING MATRICES
•save NAME
–saves ALL the variables in your workplace, regardless of differences in format, on file NAME.mat
–Type:
–> clear all %CHECK WORKSPACE
– %CHECK CURRENT DIR.
–> load Worlds
save NAME var1 var2
–specifies which variables to save in file NAME.mat
•if you want to ADD stuff to a current mat file:
–save NAME var1 -append
wilcard *
•save avariables a* %saves all variables starting with a in file avariables.mat
reading text is different than reading numbers, but you can transform one into the other:
–num2str: transforms numbers into strings
–int2str: transforms integers into strings
–mat2str: transforms 2D matrices into strings
–char: convert to character array.
–print to screen: sprintf
–print to file: fprintf
–read from string: sscanf
–read from file: fscanf
---------file operation---------
fid = fopen(filename)
–fclose(fid) %0 means success.
firstline = fgetl(fid)
•%don’t suppress output.
–nextline = fgets(fid)
% fgetl reads a line but does NOT copy the end of line character to the string. fgets does.
feof(fid) : 0 while not end of file , 1 once it is found.
fprintf(fileID, PRINTING FORMAT, variable).
•Most common conversion characters.
–%c single character
–%d decimal notation
–%s string of characters
–INSIDE PRINTING area:
•\n new line
Rather than printing the text to the screen, let’s transfer it to another file.
–newfid = fopen(‘newgoldi.txt’,’w’);
–fprintf(newfid, ‘%s \n’, newline);
–
–‘w’ means write to this new file.
–‘r’ means open to read.
–‘rt’ reads as text.
–‘a’ means append (add at the end).
FIND SPACE CHARACTERS IN FIRST LINE.
–> spaces = find(firstline == ' ')
strcmp: compare whether two strings are the same
Intermixing text and variables
•fprintf('This is trial %2d.\n', trial);
•for count=1:10
–fprintf('This is trial %2d, and condition %d\n.',trial(count), condition(count));
–end;
Exercise --result display:
•Create a three column matrix with:
•first column: numbers from 1-10.
•second column: alternating 0-1.
•third column: random number between 150 and 1000.
•WRITE TO screen:
–think trial number, condition, RT.
Answer--
data = zeros(10,3);
data(:,1)=1:10;
data(:,2)=mod(data(:,1),2);
data(:,3)=rand(1,10)*850 +150;
%writes data column-wise.
%Treats matrix as comma-delimited list.
%CONTINUES EXECUTION until all the specified variables HAVE BEEN PRINTED.
%what we want is:
%data': the transposition of data
fprintf('%2d %d %3.1f\n',data');
Last issue.
•How do you print a ' or % or \ with fprintf?
ex: it's a beautiful day!
ex: I'm 100% certain 2\4=2.
•
•Answer: you double the escape character to make it printable (page17)
•> fprintf('I''m 100%% certain 2\\4=2.')
###########IMAGE###########
IMAGES (1) p. 22
•Let's play with Matlab's demo:
•Type:
•> clear all
•> load durer %check workspace.
•> image(X) %what happened?
•> colormap(map) %ruminate on this…
•> axis equal
•> axis image %same as equal, but image fits tightly
•> axis off %turns off tick marks
Other types of images
•You can load TIFF, JPEG, BMP… with
•imread
•[X,map] = imread(filename,ext);
Write images to files
•Let's make and save a random b/w mask image.
• imwrite(matrix,'nameoffile','extension')
%imwrite(matrix,colormap,'nof','ext') for indexed images
mask = rand(400,400);
imwrite(mask,'mask','bmp');
clear all
[x,map]=imread('mask','bmp');
image(x);
colormap(map);
•Let's make and save a random color-noise mask image -unindexed
•> mask2 = rand(400,400,3); %why 3?
•> imwrite(mask2,'mask2','jpg');
•> clear all;
•> input('click key when ready');
•> X = imread('mask2','jpg');
•> image(X);
•> colormap(map);
•> input('click key when ready');
•> colormap(hot);
Matlab homework5
1. durernoise.m
Create a program that creates 5 different versions of the durer image with increasing levels of noise, using the same grayscale(256) CLUT, all in one single image (BMP).
Level of noise is measured the deviation of the noise from the actual value of the pixel.
use the following as an example:
>> z = mod(X + (rand(size(X)).*32 - 16),128);
>> image(z)
%Goal:
%Create a program that creates 5 different versions of the durer image with
%increasing levels of noise, using the same grayscale(256) CLUT, all in one
%single image (BMP).
load durer;
colormap(gray(256));
% create the image with noise
NoiseLevel1=mod(X+(rand(size(X)).*4-2),128);
NoiseLevel2=mod(X+(rand(size(X)).*8-4),128);
NoiseLevel3=mod(X+(rand(size(X)).*16-8),128);
NoiseLevel4=mod(X+(rand(size(X)).*32-16),128);
NoiseLevel5=mod(X+(rand(size(X)).*64-32),128);
combine=[NoiseLevel1'; NoiseLevel2';NoiseLevel3';NoiseLevel4';NoiseLevel5'];
image(combine');
% to polish the graph
axis off;
axis image;
xlabel 'Figure 1. Durer image with increasing levels of noise from left to right';
% write image
imwrite(combine',gray(256),'Durer.bmp','bmp');
Indexed image:
load durer; %gives me X and map
%I am going to create five matrices Xnoi which will be copies of X with
%increasing noise
Xnoi = X + rand(648,509).*60 -30; %noise here is created by randomly
%varying the luminance of a pixel
%the total range of luminance is
%124, so 30 is about 1/4 of that.
%PROBLEM: some indeces will be lower than 1 or larger than 128...
% so we correct for that. However you would like to do it!
below = find(Xnoi < 1); %find values of Xnoi that go below the colormap %index of 1
Xnoi(below) = 1; %for those values, we reassign a low luminance %value.
% the same in all cases!
above=find(Xnoi>128); % we do the same for indeces larger than 128.
Xnoi(above)= 128;
2. rgbnoise.m
Create a programm that takes the visionlab jpg logo and presents it in 2 different levels of black and white noise and two different levels of color noise, all in one single image that includes the untouched original. 3. Submit both images and corresponding script files.
www.psych.uiuc.edu/~alleras/courseImages.htm
Intermixing text and variables
textread
function.
•
•SYNTAX:
•A = textread('filename') transforms data in filename into Matrix A.
•ONLY WORKS WITH HOMOGENEOUS Matrices.
= v ns = "urn:schemas-microsoft-com:vml" />= o ns = "urn:schemas-microsoft-com:office:office" />= p ns = "urn:schemas-microsoft-com:office:powerpoint" />
•SYNTAX:
•[A,B,C] = textread('filename','%s%d%f')
•reads each column into a variable, of specified type.
strings are saved in "cell" arrays (multidimensional arrays whose elements are copies of other arrays, here a table of strings of different sizes).
names(1) is the cell itself
•so trash = name(1) makes trash a cell
•names{1} refers to the value in the cell
•so trash = name{1} makes trash a character array
•names{1}(j) is the jth element in the character array stored in the cell 1.
USE strcmp(string1,string2)
which is true if string1==string2.
name2f = input('what student?','s');
numstu = size(name,1); %number of rows
for findex=1:numstu
if (strcmp(name2f,names{findex}))
whichisit =findex;
end;
end;
Matlab homework6
for
vowel=['a' 'e' 'i' 'o' 'u']
string = [
'let' vowel '.gif'] %concatenate file name string
[letter,map]= imread(eval(
' string '));
image(letter);
colormap(map);
axis
off;
axis
equal;
input(
'Ready for next? \n');
end
;
for n=1:10
Avoid loops.
Psychtoolbox Win 2.54 (20 February 2004) requires Matlab 6.5 (Student or regular) or better.
Download zip archive (3.1 MB)
IMPORTANT UPDATES TO Win 2.54:
After you download Win Psychtoolbox 2.54, replace bug-ridden files with improved versions listed below:
WaitSecs.dll - Get it here.
CopyText.dll - Get it here.
1. Structures
Multidimensional array elements accessed by textual designators. Each field can contain any type of Matlab data (numbers, strings, cells, etc).
Type:
Data.trial = 1;
Data.setsize = 3;
Data.tgtword = 'doctor';
Data.rt = 541;
Data.resp =1;
Data
Using the "struct" function:
Data = struct('label1', dummy1, 'label2',dummy2, etc);
Creates the structure:
data.label1 = dummy1
data.label2 = dummy2
Data(64) = struct('label1', dummy1, 'label2', dummy2, etc);
Access each element like a vector:
Data(34).label1 = 234;
data(n) =struct('field1',value1,'field2',value2)
initializes only the nth value. Others are set to empty matrices.
data = repmat(struct('trial',1,'rt',-1),1,64);
This way ALL values are initialized with values specified in the struct function.
Or: Use values saved in a cell array.
> a = cell(3,1);
> a{1} = 'bob';
> a{2} = 'where are you?';
> a{3} = 'I am here';
> data = struct('line',a);
What's data(2).line?
Planning an experiment
section 1:SETUP VARIABLES
-Initialize CONSTANTS (refresh rate)
-Initialize Variables (with comments so you know what each variable does)
-Load big files (images, sounds, mex…)
Section 2:BALANCE CONDITIONS
BALANCE your design:
-define conditions
-how many trials for each condition
Section 3: TRIAL LOOP
3.1 DRAW constant images
(fixation, blank screens)
3.2 Start Trial Loop
3.2.1 Draw trial specific stimuli (if any)
3.2.2 Present stimuli
3.2.3 Get response
3.2.4 Classify response (error?)
3.2.5 ERASE ANY TRIAL SPECIFIC STIMULI
Section 4:Save DATA
Open a subject file and write data to it. (personal preference).
save data after each block/trial to avoid data loss or software crash.
Section 5:CLEAN UP
Clear all the variables you used and
the images you created, and close
any opened files.
AND DON'T FORGET TO COMMENT AS MUCH AS YOU CAN!!!
AND DON'T FORGET SECTION 0: Comments at beginning of file for
"help".
The Psychophysics Toolbox
A set of functions to:
-Interact with Monitor (pg. 27-32)
-Interact with Keyboard and mouse
-Interact with your OS (Here, Windows XP)
Screen function:
-Function that helps us interact with our monitor.
- Many "sub-functions".
First thing:
OpenWindow:
[windowPtr,rect]=Screen(0,'OpenWindow',[color],[rectangle],[pixelSize]);
windowptr: a pointer to the space in memory we are allocating to work on this window (kinda like fid=fopen(..) keeps track of a file), can be called "fixation display",'practice' etc.
rect: (if specified, and I suggest you do) gives you the coordinates of the window you’ll be using in pixels, on the format [Xtop-left, Ytop-left, Xbotton-right, Ybottom-right]. e.g. [0 0 1280 1024]
0: refers to the main monitor (where you'll be presenting stimuli).
color: you want the window to be: if one number: an index (CLUT, between 0-255), or a RGB triplet [r g b]. Later we'll talk about
changing the CLUT.
rectangle: ignored in windows
pixelsize: you can set the pixelsize for your screens (8 bit -> 256 colors, 24 bit…). Default is unchanged.
Close Window
Two ways:
To close all windows:
Screen('CloseAll');
To close a specific window:
Screen(windowPtr,'Close');
VERY IMPORTANT!!!
"Hello World " to psychtoolbox
warning
off MATLAB:DeprecatedLogicalAPI
[windowPtr,rect]=Screen(0,
'OpenWindow',255); % CLUT 255 for white background, 0 for black
Screen(windowPtr,
'DrawText','Hello World',500,350,100);
KbWait; %wait for the user to push a key
Screen(
'CloseAll');
DETERMINE HOW LONG IT TOOK MATLAB
TO OPEN THE WINDOW AND WRITE TEXT
TO IT.
Use: GetSecs (returns seconds since computer was turned on);
OffScreenWindows
So, we can work "offline", prepare our screens and then quickly copy
them to the screen.
image = Screen(windowPtr,'OpenoffScreenWindow',color,smallerrect)
image is pointer to refer to this offscreen window
windowPtr is pointer to the monitor window (to which all windows are related)
smallerrect is size of offscreen window (can be smaller!)
So, Once we have our offscreen window, we THEN copy it to our main window.
Screen('CopyWindow', srcWinPtr,DestWindoPtr, [srcRect],[dstRect]);
srcWinPtr: is the windowPointer (name) of the window you want to copy (source)
Bugs: The color template in open window subcommand is BGR instead of RGB. The following command will create blue background.
[window,rect]=Screen(0,'OpenWindow',[255 0 0]);
image = Screen(window,
'OpenoffScreenWindow',[255 0 0],[0 0 100 100]);
HideCursor;
beep=MakeBeep(100,5);
Snd('Open');
PutImage
Screen(windowPtr,'PutImage', imagearray,[rect],[copymode]);
imagearray is a matrix like the ones we created a few weeks ago:MxN or MxNx3 (if 16 or 32 bits graphic card)
Help on Screen functions?
Type:
Screen(‘NameOfFunction?’)
Try:
Screen(‘PutImage?’)
Beeps and Wav sounds
Matlab can play wav sounds and beeps WHILE doing something else
(nice for experiments).
Just like we 'Open' a window, we need to 'Open' a sound channel:
Snd('Open');
and 'close' it when you are done:
Snd('Close');
Beeps
You can create beeps with MakeBeep, which creates a vector that will be interpreted by your sound card (just like a matrix of numbers is interpreted by your graphics card as an image).
beep = MakeBeep(frequency,duration,samplingrate);
Then you can play that beep:
Snd('Play',beep,samplingrate);
Wav files
Windows Audio files:
-> wavplay(y,FS) plays sound recorded in y vector at the sampling frequency specified in FS (same sound will be different if played faster (larger FS) or slower (smaller FS). For stereo playback, Y would be N-by-2 matrix (left, right channels).
->important:
wavplay(y,FS,'async') allows you to play that sound while continuing to do stuff in Matlab (non-blocking call).
Synchronizing windows and monitor
To do so, we use the 'WaitBlanking' command in Screen.
Calling:
Screen(windowptr,'WaitBlanking')
will wait until your gun moves to the top of the monitor. (only true for CRT monitors and analog LCDs)
counting time with refresh rates:
->IF you want to present a stimulus for a specific amount of time, count time in refreshes.
TIME
counting time with GetSecs:
Cool and accurate. You can do something like:
t1=GetSecs;
t2=t1;
Screen('CopyWindow'…); %or whatever…
while ((t2-t1)< presentationTime)
t2=GetSecs;
end;
%This syntax is equivalent to WaitSecs.
tic (start counting time)
toc (count the time. )
###Get the refresh rate of monitor#######
warning off MATLAB:DeprecatedLogicalAPI
[windowptr,rectangle]=screen(0,'OpenWindow',255);
Screen(windowptr,'WaitBlanking')
t1=GetSecs;
t2=t1;
counter=0;
while ((t2-t1)< 1)
Screen(windowptr,'WaitBlanking')
counter=counter+1;
t2=GetSecs;
end;
counter
Screen('CloseAll');
frames=FrameRate(window)%present stimuli 100ms. to be accurate, the multiply of the refreshrate
Screen(window,'WaitBlanking',floor(frames./10))
Keyboard Management
List of useful functions:
KbCheck: status of keyboard
KbWait: waits for Keypress (returns GetSecs)
GetChar: waits for character
CharAvail: checks event queue for characters
FlushEvents: help manage event queue
EventAvail: checks for events
KbCheck
IS USEFUL TO CLEAN THE KEYBOARD
BUFFER!!
while KbCheck end;
will "clean" your buffer
(Technically, wait until it is clean)
[keyisDown,secs,keyCode]=KbCheck;
find(keyCode) which key in ASCII
or you can ask directly if a given key was hit:
if keyCode('Z') (would be 1 if the z key was hit)
%note capitalization.
KbName: toolbox function that allows us to name the different keys on the keyboard (primary label) (Note: '5' vs. '5%')
Usage: KbName(arg) if arg is a string ('z'): returns the keyCode for that key if arg is the array keyCode, KbName returns the label of the key.
KbName deals with KEYS not Characters!
leftTarget = KbName('left');
MOUSE Management
List of useful functions:
HideCursor
ShowCursor
GetClicks
GetMouse
SetMouse
[x,y,buttons]=GetMouse(windowPtr);
PsychDemos
If you are wondering what kind of thing you can do with PTB and how some of your
ideas can be coded up, look at the demos that ship with PTB. Try typing:
>>help PsychDemos
This will give you a list of available demos and a short description of what they do. If you are curious what a certain
demo does you can inquire further. For example, type:
>>help MandelbrotDemo
This will tell you what this script does. If you are curious how this is implemented, type:
>>edit MandelbrotDemo
This will open the file MandelbrotDemo.m in an editor window. Don’t edit this file! You might cause some damage.
Instead, save the file under a new name. For example, ‘myMandelbrotDemo.m’. Now you can twiddle things in the file
and try to see what effect these changes have on the execution of the program. But before you start doing that, let’s get
acquainted with the single most important function in Psychtoolbox.
quesdlg
ButtonName=questdlg(Question,Title,Btn1,Btn2,
DEFAULT);
-up to three buttons.
-Default is optional.
ButtonName=questdlg('What is your wish?', ...
'Genie Question', ...
'Food','Clothing','Money','Money');
INPUTDLG
ANSWER = INPUTDLG(PROMPT) creates an input dialog box where
users can enter text, saved in the cell array ANSWER.
PROMPT is a cell array containing the PROMPT strings.