Mauro Borgo.Alessandro Soranzo Massimo Grassi MATLAB for Psychologists Springer
Mauro Borgo ● Alessandro Soranzo Massimo Grassi MATLAB for Psychologists
Preface Psychological researchers should possess several skills,and one of them is surely creativity.Creativity is needed at several key points of the research process,such as in and designing an exp ment Creativity drives mbe a revea their full potentia. Much of this er vity I is now expres ed through a comput er program.For exam use specific software that has been dedicated to that particular job.This software might,however,be a hindrance to creativity.preventing it from permeating research This is because in the majority of cases,software is designed to satisfy the average user and it is not flexible enough to meet specific needs. In this sense.MATLAB is exactly the other side of the coin.When we first open the software,the lack of a y he fr ng:at a first e program nay se em di ing users first approach eriments and n the ro major advantage:we do not have to adapt our needs to the software;it is the soft- ware that adapts to our needs. MATLAB is an extremely powerful research tool.By means of this single soft ware tool we can control every step of our research.We can create stimuli of any kind (e.g.pictures,sounds).and we can program psychological experiments,calcu- late statisti simulations. and do kind o signal processin control and very con step of computer progrm.Moreover.knowledg of MATLAB will help you to find a postdoc in experimental psychology after com- pleting the Ph.D.In many cases,research groups look for researchers with good MATLAB programming skills. The current text is written to help the newcomer in using MATLAB for research page http://www.psy.unipd.it -gT assi/m atlab book html vii
vii Psychological researchers should possess several skills, and one of them is surely creativity. Creativity is needed at several key points of the research process, such as in creating experimental stimuli and planning and designing an experiment. Creativity drives good data analysis, so that numbers can reveal their full potential. Much of this creativity is now expressed through a computer program. For example, in planning and designing a psychological experiment and in analyzing data, we use specifi c software that has been dedicated to that particular job. This software might, however, be a hindrance to creativity, preventing it from permeating research. This is because in the majority of cases, software is designed to satisfy the average user and it is not fl exible enough to meet specifi c needs. In this sense, MATLAB is exactly the other side of the coin. When we fi rst open the software, the lack of a graphical interface may be frustrating: at a fi rst glance, the program may seem diffi cult to use. This book is aimed at helping users in their fi rst approaches to this software, to aid them in programming their psychological experiments and consequently in liberating their creativity. And this is MATLAB’s major advantage: we do not have to adapt our needs to the software; it is the software that adapts to our needs. MATLAB is an extremely powerful research tool. By means of this single software tool we can control every step of our research. We can create stimuli of any kind (e.g., pictures, sounds), and we can program psychological experiments, calculate statistics, run simulations, and do any kind of signal or biosignal processing. In brief, the fl exibility of this software lets us to control and customize every conceivable step of our research requiring a computer program. Moreover, knowledge of MATLAB will help you to fi nd a postdoc in experimental psychology after completing the Ph.D. In many cases, research groups look for researchers with good MATLAB programming skills. The current text is written to help the newcomer in using MATLAB for research in experimental psychology. However, the content can be transferred to any application. The reader can fi nd the scripts written in this book at the following web page: http://www.psy.unipd.it/~grassi/matlab_book.html Preface
Contents 1 Basic Operations. Variables. Thinking in a Matrix Way 8 Operations. 15 Summary. 17 Exercises A Brick for an Experiment 2 Data Handling 25 Types of Variables (Logical Values.Strings,NaN.Structures.Cells). Logical Variables. Strings. NaN. Cells Import/Export. Summary. Exercises. 43 A Brick for an Experiment. 44 Read the Results. 44 Reference 46 Suggested Readings 46 3 Plotting Data Plot Dat Control the Plot's Objects:Labels,Legend,Title. Subplot:Multiple Plots in One Figure. 52 3-D Plots Printing and Saving Images. 58
xi 1 Basic Operations . 1 Variables . 5 Thinking in a Matrix Way . 8 Operations . 15 Summary . 17 Exercises . 18 A Brick for an Experiment . 20 References . 23 Suggested Readings . 23 2 Data Handling . 25 Types of Variables (Logical Values, Strings, NaN, Structures, Cells) . 25 Logical Variables. 25 Strings . 31 NaN . 35 Structures . 35 Cells . 38 Import/Export . 40 Summary . 42 Exercises . 43 A Brick for an Experiment . 44 Read the Results . 44 Reference . 46 Suggested Readings . 46 3 Plotting Data . 47 Plot Data . 47 Control the Plot’s Objects: Labels, Legend, Title. . 50 Subplot: Multiple Plots in One Figure . 52 3-D Plots . 56 Printing and Saving Images . 58 Contents
Contents Handle Graphics. 86 Exercises 6 A Brick for an Experiment. Plot the Results. Reference 65 Suggested Readings 4 Start Programming M-Script and Function Control Flow Statements Cycles and Conditionals:If. Switch Case. ForL00ps. While Break. 81 Try-Catch ops Versus Matrices and If Versus Logicals. Function Change the Number of Inputs and Outputs More on Data Import/Export:Script Examples. Analysis . Guidelines for a Good Programming Style. 96 Writing Code. 96 Debug 98 100 Analysis 0Q9 References Suggested Readings. 106 5 A Better Sound. 107 Generate a sound 107 Multiple Sou 112 Man 's Level with Di ferent Waveforms. A Sound's Envelope. Sound Filtering. Sound Analysis 123 Summary 12s Exercises 125
xii Contents Handle Graphics . 58 Summary . 61 Exercises . 62 A Brick for an Experiment . 64 Plot the Results . 64 Reference . 65 Suggested Readings . 65 4 Start Programming . 67 M-Scripts and Functions . 67 Control Flow Statements. 70 Cycles and Conditionals: If . 70 Switch Case . 72 For Loops . 74 While . 78 Break . 81 Try–Catch . 82 Loops Versus Matrices and If Versus Logicals . 82 Functions . 83 Scope of Variables . 86 Change the Number of Inputs and Outputs . 87 More on Data Import/Export: Script Examples . 90 Analysis . 95 Guidelines for a Good Programming Style . 96 Writing Code . 96 Debug . 98 Summary . 100 Exercises . 101 A Brick for an Experiment . 102 Analysis . 104 References . 106 Suggested Readings . 106 5 A Better Sound . 107 Generate a Sound . 107 Multiple Sounds . 112 Manipulating a Sound’s Level . 114 Match the Level of Sound with Different Waveforms . 115 Stereophonic Sounds for ITD and ILD . 116 A Sound’s Envelope . 118 Sound Filtering. 120 Sound Analysis. 123 Summary . 125 Exercises . 125
Contents xi A Brick for an Experiment. 126 References. Suggested Readings. 128 6 Create and Proccess Images Images Basics. Importing and Exporting Images. Display Images. Basic Manipulation of Images. 135 Point Operations. 136 Intensity Transformation 136 138 ges of th e Image 144 Advance Image Processing. Creating Images by Computation 44 149 Exercises. 150 References Suggested Readings 152 7 Data Analysis 53 De easures of Central Tendency Measures of Dispersion. Bivariate and Multivariate Descriptive Statistics. Covariance. Simple and Multiple Linear Regression. 156 Generalized Linear Model 160 Inferential Statistics 162 ANOVA 66 Nonparametric Statistics Categorical Data. Ordinal Data. Signal-Detection Theory(STD)Indexes 182 Summary. 184 Exercises 185 ABrick for an Experiment 186 References 1 Suggested Readings
Contents xiii A Brick for an Experiment . 126 References . 127 Suggested Readings . 128 6 Create and Proccess Images . 129 Images Basics . 129 Importing and Exporting Images . 132 Display Images . 134 Basic Manipulation of Images . 135 Point Operations . 136 Intensity Transformation . 136 Windowing . 138 Neighborhood Processing . 140 The Edges of the Image . 144 Advanced Image Processing . 144 Creating Images by Computation . 144 Summary . 149 Exercises . 150 References . 151 Suggested Readings . 152 7 Data Analysis . 153 Descriptive Statistics . 153 Measures of Central Tendency . 153 Measures of Dispersion . 154 Bivariate and Multivariate Descriptive Statistics . 155 Covariance . 156 Simple and Multiple Linear Regression . 156 Generalized Linear Model . 160 Inferential Statistics . 162 Parametric Statistics . 162 t-Test . 163 ANOVA . 166 Nonparametric Statistics . 177 Categorical Data . 177 Ordinal Data . 179 Signal-Detection Theory (STD) Indexes . 182 Summary . 184 Exercises . 185 A Brick for an Experiment . 186 References . 187 Suggested Readings . 187
xiv Contents 8The Charm of Graphical User Interface. 189 ction GUIDE Starting GUIDE 190 The GUI Toolbar. 190 Adding UiControls to the GUI. Closing the GUI. 193 199 Ex mple aphs and Figures in the GUL 0 er Input Adding Your Own Functions. 20 A Brick for an Experiment. 212 Appendix. 215 The File Menu. 216 The Edit Menu The view menu 217 21 Preferences for GUIDE 219 Backward Compatibility. 220 Other Preferences. 221 Suggested Readings 9 Psychtoolbox:Videc 223 The screen function 223 How to Use Screen to Draw Figures. Preliminary Notions:Drawing Figures in Three Steps-Opening. Drawing,and Closing. 227 Opening the Window 227 Drawing:An Introduction 229 Closing 230 230 Drawing Shapes Batch Processing:Drawing Multiple Figures at Once. 功坊 Drawing Text.ee.e. Importing Images 238 Analysis 239 Video Clips. 240 Analys 240 Analysi 241 Drawing Things at the Right Time. 241
xiv Contents 8 The Charm of Graphical User Interface . 189 Introduction . 189 GUIDE . 189 Starting GUIDE . 190 The GUI Toolbar . 190 Adding UiControls to the GUI . 191 Closing the GUI . 193 Controlling UiControls from Other UiControls . 196 The Sum-Two-Numbers Example . 196 Displaying Graphs and Figures in the GUI . 202 Saving User Input . 204 Adding Your Own Functions . 207 A Brick for an Experiment . 212 Appendix . 215 The File Menu . 216 The Edit Menu . 216 The View Menu . 217 The Layout Menu . 217 Tools Menu . 218 Help . 218 Preferences for GUIDE . 219 Backward Compatibility . 220 Other Preferences . 221 Suggested Readings . 221 9 Psychtoolbox: Video . 223 The Screen Function . 223 Analysis . 225 How to Use Screen to Get Information . 225 How to Use Screen to Draw Figures . 227 Preliminary Notions: Drawing Figures in Three Steps—Opening, Drawing, and Closing . 227 Opening the Window . 227 Drawing: An Introduction . 229 Closing . 230 Drawing: Reprise . 230 Analysis . 231 Drawing Shapes . 231 Batch Processing: Drawing Multiple Figures at Once . 235 Drawing Text . 236 Importing Images . 238 Analysis . 239 Video Clips . 240 Analysis . 240 Analysis . 241 Drawing Things at the Right Time . 241
Contents Analysis. 243 Summary 243 Exercises 244 Solutior Exercise 2. Solution 2. 4445 A Brick for an ExDeriment. References. 248 Suggested Readings 248 10 Psychtoolbox:Sound,Keyboard and Mouse 249 Sound Functions Getting Participants'Inputs:Keyboard and Mouse Functions. Keyboard Response 253 "Press Any Key to Proceed". "Press the spacebar to Proceed 254 256 Choice Reac ion Tim Go/No-Go Rea Reaction Times Within a Video Clip. Mouse Input. Using Participants'Input to Manipulate Shape Characteristics. Keyboard Manipulations. 264 Placing Discs with the Mouse Summary. 267 Exercise 268 e, ABrick Experiment 5900坊 Suggested Readings. About the Authors. 275 Index 277
Contents xv Analysis . 243 Summary . 243 Exercises . 244 Exercise 1 . 244 Solution 1 . 244 Exercise 2 . 244 Solution 2 . 245 A Brick for an Experiment . 245 References . 248 Suggested Readings . 248 10 Psychtoolbox: Sound, Keyboard and Mouse . 249 Timing . 249 Priority . 250 Sound Functions. 251 Getting Participants’ Inputs: Keyboard and Mouse Functions . 253 Keyboard Response . 253 “Press Any Key to Proceed” . 254 “Press the Spacebar to Proceed” . 254 “Press Any Key to Respond” . 256 Reaction-Time Detection . 256 Choice Reaction Time . 258 Go/No-Go Reaction Time . 259 Reaction Times Within a Video Clip. 260 Mouse Input . 262 Using Participants’ Input to Manipulate Shape Characteristics . 263 Keyboard Manipulations . 264 Placing Discs with the Mouse . 266 Summary . 267 Exercises . 268 Exercise 1 . 268 A Brick for an Experiment . 269 References . 272 Suggested Readings . 273 About the Authors . 275 Index . 277
Chapter 1 Basic Operations This chapter gives an overview of MATLAB and compares MATLAB with a scientific calculator.The chapter gives also an overview of basic arithmetic operations and functions as well as a short introduction to matrices and matrix manipulation. computer.Wher you start MATLAB,the MATLAB desktop opens,as shown in Fig.1.1(or some thing similar,depending on your MATLAB version).In this first chapter we refer only to the Command Window,where the special >prompt appears.The other windows have the following meaning: The Workspace Window contains a list of variables that are in use in the working session. .The Command History contains the list of all commands you have typed in the command windo The Current Folder window shows the list of the files contained the folder you are working on. When the prompt>>is visible,this means that MATLAB is waiting for a com- mand.You can quit MATLAB at any time in either of the following ways: 1.Select Exit MATLAB from the desktop File menu. 2.Enter quit orexit after the command window prompt>>,and press the Enter key. Observe that the tab above the Workspace shows the Current Directory Window For example,in the Windows operating system,the path might be as follows: C:\MATLAB\Work,indicating that directory "Work"is a subdirectory of the main directory "MATLAB,"which is installed in drive C.Clicking on the arrow in the Current Directory Window shows a list of recently used paths.Clicking on the but ton to the right of the window allows the user to cha e the current directory Knowing which is the current path is fundamental:from the and Window you
M. Borgo et al., MATLAB for Psychologists, 1 DOI 10.1007/978-1-4614-2197-9_1, © Springer Science+Business Media, LLC 2012 This chapter gives an overview of MATLAB and compares MATLAB with a scientifi c calculator. The chapter gives also an overview of basic arithmetic operations and functions as well as a short introduction to matrices and matrix manipulation. It is supposed that you have already installed MATLAB on your computer. When you start MATLAB, the MATLAB desktop opens, as shown in Fig. 1.1 (or something similar, depending on your MATLAB version). In this fi rst chapter we refer only to the Command Window, where the special >> prompt appears. The other windows have the following meaning: • The Workspace Window contains a list of variables that are in use in the working session. • The Command History contains the list of all commands you have typed in the command window. • The Current Folder window shows the list of the fi les contained the folder you are working on. When the prompt >> is visible, this means that MATLAB is waiting for a command. You can quit MATLAB at any time in either of the following ways: 1. Select Exit MATLAB from the desktop File menu. 2. Enter quit or exit after the command window prompt >> , and press the Enter key. Alternatively, select File with the mouse from the top menu bar, and then exit MATLAB. Observe that the tab above the Workspace shows the Current Directory Window. For example, in the Windows operating system, the path might be as follows: C:\MATLAB\Work, indicating that directory “Work” is a subdirectory of the main directory “MATLAB,” which is installed in drive C. Clicking on the arrow in the Current Directory Window shows a list of recently used paths. Clicking on the button to the right of the window allows the user to change the current directory. Knowing which is the current path is fundamental: from the Command Window you Chapter 1 Basic Operations
2 I Basic Operations Fig.1.1 The MATLAB desktop.MATLAB release 2011 have stored in the given directory.It is,of cous possible o change your working directory. Before continuing our introduction to MATLAB,we want to highlight a very useful window:the HELP Window.This window is the most useful window for beginning MATLAB users-and for expert users as well:select Help PRODUCTHELP from the top bar menu.The Help Window has most of the fea- tures you would see in any web browser,including clickable links,a back button and a search engine.All MATLAB commands and functions are explained with amples:you pegin with a description of language.The word MATLAB"is the concatenation of the words MATrix LABoratory,meaning that MATLAB is an interactive software system for numerical computation,especially designed for computations with matrices.Before going into the details of matrix computations,let us first see how to use MATLAB to do simple arithmetic opera- tions:Type 1+1 after theprompt,followed by Enter:that is,press the Enter key. as indicated by >1+1 MATLAB gives its quick answer by displaying the following message: ans 2
2 1 Basic Operations have access to the fi le stored in the given directory. It is, of course, possible to change your working directory. Before continuing our introduction to MATLAB, we want to highlight a very useful window: the HELP Window. This window is the most useful window for beginning MATLAB users—and for expert users as well: select Help► PRODUCTHELP from the top bar menu. The Help Window has most of the features you would see in any web browser, including clickable links, a back button, and a search engine. All MATLAB commands and functions are explained with examples: you have simply to search for the desired word. Now let us begin with a description of the MATLAB language. The word “MATLAB” is the concatenation of the words MATrix LABoratory, meaning that MATLAB is an interactive software system for numerical computation, especially designed for computations with matrices. Before going into the details of matrix computations, let us fi rst see how to use MATLAB to do simple arithmetic operations: Type 1+1 after the >> prompt, followed by Enter; that is, press the Enter key, as indicated by >> 1+1 MATLAB gives its quick answer by displaying the following message: ans = 2 Fig. 1.1 The MATLAB desktop. MATLAB release 2011b
1 Basic Operations 3 divis ion,and MATLAB always returns the correct result.If such is not the case,ther is certainly something wrong with what you typed.For example,you can try the following operations(type the operation after the>>prompt followed by Enter): MATLAB answer Meaning of the operation 35*12 ans=420 Multiplication 2/45 ans=0.0444 Division -1 an■3 Subtraction 23 ans=8 Exponentiation Note that to type numbers such as the Avogadro'snumber3you can eithe sent the numb numbe insc ,ype6.023e2 ntissa and exponent must be sepa- rated by the letter e (or E): >6.023*10^23 >6.023e23 an26.0230e+023 an 6.0230e+023 Such numbers are also defined to be floating point. MATLAB warns you in the case of in invalid operation or"unexpected"results What do you think MATLAB will show us if we type 12/0 or 0/0?Let's try it: To TYPE after prompt>> followed by Enter MATLAB answer Meaning of the answer 12/0 ans=Inf You should not divide by zero.but if you do.the result is Infinity /0 ns =NaN Unable to find the answer.so the result is nan=not a number 11 22211+ If you want to perform this operation,you must complete the Error:Expression expression with another term or statement is incorrect As you can see.MATLAB is unable to "stay quiet."It quickly answers your commands by displaying something in the command window.In the previous cases the answer was a special value such as Inf (Infinity)or NaN (Not a Number).You can use these special values on their own,typing.for example: >>12/Inf ans 0
1 Basic Operations 3 You can perform other arithmetic operations, such as multiplication, subtraction, and division, and MATLAB always returns the correct result. If such is not the case, there is certainly something wrong with what you typed. For example, you can try the following operations (type the operation after the >> prompt followed by Enter): To TYPE after prompt >> followed by Enter MATLAB answer Meaning of the operation 35*12 ans= 420 Multiplication 2/45 ans= 0.0444 Division 4−1 ans= 3 Subtraction 2^3 ans= 8 Exponentiation Note that to type numbers such as the Avogadro’s number 6.023 × 10 23, you can either write the expression 6.023*10^23 or you can represent the number in scientifi c notation. To enter Avogadro’s number in scientifi c format, type 6.023e23, where 6.023 is the mantissa and 23 is the exponent. Mantissa and exponent must be separated by the letter e (or E): >> 6.023*10^23 ans = 6.0230e+023 >> 6.023e23 ans = 6.0230e+023 Such numbers are also defi ned to be fl oating point. MATLAB warns you in the case of in invalid operation or “unexpected” results. What do you think MATLAB will show us if we type 12/0 or 0/0? Let’s try it: To TYPE after prompt >> followed by Enter MATLAB answer Meaning of the answer 12/0 ans= Inf You should not divide by zero, but if you do, the result is Infi nity 0/0 ans= NaN Unable to fi nd the answer, so the result is NaN = Not a Number 11+ ??? 11+ | Error: Expression or statement is incomplete or incorrect If you want to perform this operation, you must complete the expression with another term As you can see, MATLAB is unable to “stay quiet.” It quickly answers your commands by displaying something in the command window. In the previous cases, the answer was a special value such as Inf (Infi nity) or NaN (Not a Number) . You can use these special values on their own, typing, for example: >> 12/Inf ans = 0