Professional Documents
Culture Documents
Matlab For Psycologists: CDL Scienze E Tecniche Psicologiche A.A. 2018-2019
Matlab For Psycologists: CDL Scienze E Tecniche Psicologiche A.A. 2018-2019
ANDREA FROSINI
e-mail: andrea.frosini@unifi.it
Testo di riferimento:
M. Borgo, A. Soranzo, M. Grassi
“MATLAB for Psycologists”
Springer
Task: enjoy updating variables and make arithmetical operations on them. Keep track
of their changes in the Workspace.
N.B. Using semicolon ; at the end of a command prevents the command to be echoed on the screen
>>c=[1,2,3,4;5,6,7,8;9,10,11,12];
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8
9 10 11 12 9 10 11 12 9 10 11 12 9 10 11 12
Ans= 4 Ans= 567 Ans = 1 Ans =
12 5 c= 1 3
9 5 7
9 11
The function logical(x) converts the elements of the vector x into logical values
N.B. the example in cell (1,5) needs a further comment: MATLAB resolves the
command 0<x<2 as follows
1) it computes 0<x that is true so it gives 1 as result;
2) it computes 1<2 that is true, giving 1 as Ans.
>>sprintf(‘Il nome del mio amico e’’ %s ed ha %d anni’,a,eta(1)) Special characters spec.:
Ans= Il nome del mio amico e’ Mario ed ha 21 anni %c – single char
>>sprintf(‘Il nome del mio amico e’’ %s ed ha %d anni’,b,eta(2)) %d – integer number
Ans= Il nome del mio amico e’ Luigi ed ha 22 anni %s – string of chars
%f – decimal number
\n – newline
\t – horizontal tab
INPUT
>>input (‘How old are you? ’) >>input(‘How old are you?’,’s’) >>a= input(‘Name a friend ’,’s’)
How old are you? 35 How old are you? Thirty five Name a friend Luca
Ans = 35 Ans = Thirty five a = Luca
% ‘s’ is for string inputs
>>subject.name=‘Mario’ >>subject(2).name=‘Luigi’
>>subject.surname=‘Rossi’ >>subject.age=20
>>subject.age=24 >>subject.testanswers=[1,1,2,2,2]
>>subject.testanswers=[2,1,4,1,2] >>subject(2)
>>subject.testcorrections=logical([1,0,0,1,1]) Ans =
>>subject name: ‘Luigi’
Subject= surname: []
name: ‘Mario’ age : 20
surname: ‘Rossi’ testanswers : [1,1,2,2,2]
age : 24 testcorrections :
testanswers : [2,1,4,1,2] >>rmfield(subject,’testanswers’)
testcorrections : 1 0 0 1 1 Ans = name
surname
testanswers
testcorrections
Import/Export:
In MATLAB it is extremely useful to save and load variables to and from files for
further working sessions, since the program deletes them as soon as you quit.
Useful hints: x=[0:0.2:1] lists all the values from 0 to 1 with 0.2 step, i.e.,
x=[0,0.2,0.4,0.6,0.8,1], y=3*x creates a vector y=[0,0.6,1.2,1.8,2.4,3]
>>x=[0:0.2:1] >>plot(x,y,x,x.*x)
x= 0 0.2 0.4 0.6 0.8 1 % .* is the element by
>>y=3*x element product in
y=0 0.6 1.2 1.8 2.4 3 vectors
>>plot(x,y)
There are several plot command options to set the appearance of the figure: line aspect, line color,
axes width, legenda, title, labels etc… They will be treated if needed.
Exercises at will
Syntax Semantic
if condition
If condition is true then statement1 is
statement1 performed and go to end, else
else statement2 is performed.
statement2
end Multiple conditions
>> Test_if
Insert a number greater than zero: 45
>>true
false true
x>0
Test_mult_if.m
x=input(‘Insert test result [0-30]:’);
if x<18 output output
disp(‘try again’) ‘false’ ‘true’
elseif x<30
disp(‘Good result: you pass!’)
elseif x=30
disp(‘Awesome!!!’)
else
disp(‘you cheater’)
end;
end
>> Test_mult_if
Insert test result [0-30]: 28
Informatica
>> Good result: you pass! Andrea Frosini 21
Chapter 4- Start Programming
Control flow statements
Cycles and Conditionals: if
false true
x<18
Test_nested_if.m output
false true ‘failed’
x = input('Insert test result [0-30]:','s'); x<=30
if str2num(x)<18
disp('you failed')
elseif str2num(x)<=30 output output
disp('Good result: you pass!') ‘cheater’ ‘pass’
if strcmp(x,'30')
disp('Awesome!!!')
end;
else
disp('you cheater') false true
end; x=30
>> Test_nested_if
Insert a number greater than zero: 30 output
>>Good result:you pass! ‘Awesome’
>>Awesome!!!
Syntax Semantic
for var in list_of_values The variable var takes all the values in
statement list_of_values and for each of them
end statement is performed
for var in start:step:stop The variable var takes all the integer
statement values from start to stop each time
end increasing/decreasing of step and for
each of them statement is performed
initialization
of var
Test_for.m
for var=3:2:10
disp(‘the value of var is %d’,var)
end;
condition
>> Test_for false
3
5
7
9 true
statement
When a function is called, the variables defined inside it are created (if already present
the old ones are frozen) and lasts till the end of the function. Those variables are
called LOCAL VARIABLES.
GLOBAL VARIABLES: usually written in capital letters, they are defined in the
workspace and the are accessible from all the procedures.
PERSISTENT VARIABLES: they can be defined only inside functions and live in the
space where they are created. They persist between successive calls of the function.
Handling files (creating, saving, updating them) is not an easy task: the general
philosophy that lies behind these actions involves the use of an integer pointer
variable (say handler), i.e., a number that keeps track of the last examined symbol of
the file.
The last symbol of a file is called eof (End of File).
Wooow
To interact with a file, it has to be It’s
interesting
- opened (the pointer is set in its first position);
- read (the pointer increases its value by one or more positions);
- updated (a symbol can be changed or new symbols can be added at its end);
- closed (the pointer variable is trashed) after its use.
function displayfile(filename) fopen(filename) open the file filename and set the handler
x to its first position.
x=fopen(filename);
while ~(feof(x)) feof(x) checks if x reached the last position of the file,i.e.,
theeof position, and returns the related boolean.
line=fgetl(x);
disp(line); fgetl(x) read the file from the handler till the end of the
end line.
fclose(x);
fclose(x) close the file by unsetting its handler x.
end
The other reading/writing commands may have different options too, that will be
used if needed.
Harmonic 250 Hz sound (sawtooth wave) Inharmonic sound - different frequencies composition
The last example shows how to generate a small melody of a couple of seconds by
simply concatenating 5 different sounds
The remaining part of the Chapter (pgg.113-125) goes deep into the sound
creation and manipulation, and it is skipped here.
% choose a small colored image, say icon.bmp In our example, the obtained matrix has dimension
A=imread(‘icon.png’,’png’) 128*128*3 since each pixel is expressed in RGB values
% imported matrix is displayed in numeric format raging from 0 to 255 (8 bits representation).
image(A) No further infos are present so using the command
% image is displayed [A,B]=imread(‘icon.png,’png)
imwrite(A,’icon2.png’,’png’) B turns out to be void.
% icon2 is created in the default folder Images may have a proper palette table as additional info,
that, in case, is imported into B
Exercise:
create a random 128 x 128 image and display it changing the colormap
All the functions have a standard syntax and are easy to use when needed
3. Run >>SetupPsychtoolbox
4. Answer ‘no’ and then ‘yes’ to the Matlab requests. Finally press enter two times.
Example Comments
Example Comments
[myscreen, rect]=Screen(‘OpenWindow’,0,[0,255,0]); Open a window of the same size as the screen, and
make it green.
Myscreen is a pointer to the screen, while rect is a
4-tuple with top-left pixel and the bottom-right
pixel coordinates.
Myrect=[10,20,150,250];
Screen(‘OpenWindow’,0,[],Myrect); Open a new rectangular window whose top-left
pixel and the bottom-right pixel coordinates are
(10,20) and (150,250) of the default white color.
Closing
To close the window and destroy the pointer simply write
Screen(‘CloseAll’)
If we open more than one window, then we can destroy a single one, i.e., its pointer,
say pippo, using
Screen(‘Close’,pippo)
Informatica Andrea Frosini 62
Chapter 9 – Psychtoolbox: Video
Drawing: an Introduction and Reprise
The use of Flip command: when one or more figures are drawn, they are saved in
the background memory (backbuffer) and so not visible.
The Flip subfunction moves the figures from the backbuffer to the foreground
memory (frontbuffer), and so they become visible.
When Flip is executed, the backbuffer is cleared and the frontbuffer is updated.
Sintax is:
Screen(‘Flip’,windowPtr)
where windowPtr is a pointer to the chosen screen.
Example Comments
[pippo,pluto]=Screen('OpenWindow',0,[],[10,20,100,200]); A white small rectangular area is depicted on the
top of the screen.
pippo
Example Comments
[pippo,pluto]=Screen('OpenWindow',0,[],[10,20,100,200]); A white small rectangular area is depicted on the
top of the screen.
Example Comments
try
[mywin, mywindim]=Screen(‘OpenWindow’, 0, [0,255,0]); mywindim contains the dimensions of the full screen
Drawing Text:
The sub-function DrawText allows one to draw text on the screen. The sintax is
Screen(‘DrawText’, windowPtr, text [, x] [, y], [, color] [, …]);
where x and y are the coordinates of the top left corner of the starting text.
The DrawText sub-function returns the coordinates (x,y) of the ending point of the
inserted text.
Example Format the text
try Screen(‘TextStyle’,pippo,n)
pippo=Screen(‘OpenWindow’,0,[0,255,0]); % set the textstyle of the window pippo
MyText=‘Ciao Mario’; % n ranges from 0 to 7 to have normal, bold, italic …
Screen(‘DrawText’, pippo, MyText,40,50,[255,0,0]); Screen(‘TextFont’,pippo,’Verdana’);
Screen(‘Flip’,0); % changes the font into Verdana
KbWait; Screen(‘TextSize’,pippo,36)
Screen(‘CloseAll’); % set the textsize to 36
catch
disp(‘errore’); % all those sub-functions return the previous value of
end the changed format
try
[pippo,dim]=Screen(‘OpenWindow’,0,[],[100,100,700,700]);
cheers=[‘’Ciao’’,’’Hi Hi’’,’’Bonjour’’,’’Hola’’]; An array of strings is created
Screen(‘TextFonts’,pippo,’Arial’);
Screen(‘TextSize’,pippo,40);
for i=[0:10:255] We use the function randi( ) for a quick way to
x=randi(dim(3)); generate random integers.
y=randi(dim(4));
MyCheers=char(cheers(randi(4))); % WARNING!!! Warning: the sub-function DrawText requires an
Screen(‘DrawText’,pippo,MyCheers,x,y,[i,0,0]); array of char as text input, so we have to change
Screen(‘Flip’,pippo); the type of cheers from string to char!
pause(0.1);
end Remind that the assignment of a text string to a
KbWait; variable can be done using single quotes, i.e., the
Screen(‘CloseAll’); type will be array of characters, or double quotes
catch …end i.e., the type will be a single string.
Example Comments
try
A=imread(‘mandrill.jpg’,’jpg’);
r=[0,0,size(A)];
[pippo,dim]=Screen(‘OpenWindow’,0);
r=CenterRect(r,dim);
pic=Screen(‘MakeTexture’,pippo,A); Pic is a pointer to the created texture
Screen(‘DrawTexture’,pippo,pic,[],r); Pic is inserted inside the rectangle r and drawn in
Screen(‘Flip’,pippo); the backbuffer. N.B. the texture and the rectangle
KbWait; must have the same dimension.
Screen(‘CloseAll’);
catch …end
try
[pippo, dim]=Screen('OpenWindow',0,[255,0,0],[100,100,700,700]);
discdiam=20;
disc=[0 0 discdiam discdiam]; Use of AlignRect: align the rectangle
rect=[200 200 400 400]; disc inside the biggest rectangle rect
disc=AlignRect(disc,rect,'center','left'); centering disc on the y-coordinate and
for i=0:180 posing on the left the x-coordinate
Screen('FillRect',pippo,[255,255,255],rect);
Screen('FillOval',pippo,[0 0 0],[disc(1)+i,disc(2),disc(3)+i,disc(4)]);
Screen('Flip',pippo);
pause(0.01);
end
Screen('CloseAll');
Sound Functions
There are some functions to synthesize and play sounds that are extremely useful
for psychological experiments.
The main is PsychportAudio whose use is similar to that of Screen.
To play a beep of a given frequency f, duration time d and sample ratio sr type
MakeBeep(f,d,sr);
Example Comments
try
f=500; N.B. the sample ratio of 44100 is not
d=1; always supported. In case use 48000.
sr=48000; The Open sub-function contains among
beep=MakeBeep(f,d,sr); % the beep is generated others, the sound ratio of the sound
%InitializePsychSound; that will be played and the number of
pippo=PsychPortAudio('Open', [], [], [], sr, 1); channels, i.e., how many different
PsychPortAudio('FillBuffer',pippo,beep); sounds will be played together.
PsychPortAudio('Start',pippo);
PsychPortAudio('Stop',pippo,d);
catch
disp('errore');
end
One can switch between code of a keyboard key and its name by means the function
KbName().
Example: KbName(‘c’) returns the code 67, and KbName(67) returns the character
‘c’.
try try
[pippo,rect]=Screen(‘OpenWindow’,0) [pippo,rect]=Screen('OpenWindow',0);
DrawFormattedText(pippo,’PRESS ANY KEY TO_ DrawFormattedText(pippo,'PRESS SPACEBAR TO
PROCEED’,’center’,’center’); PROCEED','center','center');
Screen(‘Flip’,pippo); Screen('Flip',pippo);
KbWait, spax=KbName('space');
Screen(‘CloseAll’); [tmp,code]=KbWait;
catch while code(spax)==0
disp('errore'); [tmp,code]=KbWait;
End end
Screen('CloseAll');
catch
disp('errore');
end
In Exercise ‘Animals’ add the possibility of answering by clicking with the mouse on
two red and green rectangles on the left and on the right of the word. Furthermore,
take care of the reaction time of each player.
Read till the end of the chapter
Exercise Animals
Mouse click on two buttons and get the answer Create two buttons on a [0 0 400 400] rectangle
script bottoni
[clicks,x,y,button]=GetClicks;
push1=[50, 300, 100, 350];
disp([x y]);
if ((x>50)&(x<100)&(y>300)&(y<350)) push2=[300, 300, 350, 350];
answr="a"; Screen('FillOval',pippo,[0 255 0],push1);
elseif ((x>300)&(x<350)&(y>300)&(y<350)) Screen('DrawText',pippo,'A',60, 305);
answr="o"; Screen('TextColor',pippo,[0 0 255]);
else Screen('FillOval',pippo,[255 0 0],push2);
answr="e"; Screen('DrawText',pippo,'O',310, 305);
end
if (answr==word(2,j))&(rtime<2)
results(1,i)=1;
results(2,i)=rtime;
end