2 Introduction we authors have no affiliation.MATLAB has become popular in several branches of engi neering and science,including behavioral science.Nonetheless,to the best of our knowl edge,no book has appeared about MATLAB that is written specifically with behavioral scientists in mind.Nor for that matter has a book come out for behavioral scientists about any other general-purpose programming language.The need for such a volume motivated the first edition of this book.Its positive reception encouraged us to revise the text and expand the coverage in this second edition. Will it be worth your time to read this book?Once you have gone through the text and generated your own have enough progr you need ora ing k some alyderstand and build upn thewo o MATLAB their ork leagues who use You will probably find this book most useful if you Luse it in t s.In the first ou will through it o th int to able detail and deve ng the hands-on skills that will make you a MATLAB use not just a MATLAB a In the second stag as a refer ce,rnin quickly to those secti ons that t your own programming needs. To make the book as useful as possible as a reference source.we have designed it so you can get the examples you need quickly and easily.You can do so by turning to the opening page of any chapter and finding there a list of things you may want to do.Beneath that list is a compendium of associated commands.The text itself provides examples you can adapt for your own purposes.You can copy those examples by hand into your own programs. or,to avoid typographical errors,you can copy and paste them from the website associ- ated with this book(www.routledge.com/9780415535946).where the programs and their outputs are available,along with the solution to selected problems.Finally,the list of com- mands introduced in each chapter is listed as well in the Commands Index. 1.2 Getting an Overview of This Book Acquiring a new skill such as computer programming can be daunting.so it helps to have an overview of what you can expect as you proceed.Here,then.is a roadmap of the con- tents of this book.Besides signposts,we also provide brief explanations of the goals of each chapter. 1.Introduction.By reading the present chapter.you will lear more than you may ou w how to activate MATL L.Save.a program
2 Introduction we authors have no affiliation. MATLAB has become popular in several branches of engineering and science, including behavioral science. Nonetheless, to the best of our knowledge, no book has appeared about MATLAB that is written specifically with behavioral scientists in mind. Nor for that matter has a book come out for behavioral scientists about any other general-purpose programming language. The need for such a volume motivated the first edition of this book. Its positive reception encouraged us to revise the text and expand the coverage in this second edition. Will it be worth your time to read this book? Once you have gone through the text and generated your own MATLAB programs based on the material presented here, you should have enough programming skill to do most of what you need to for your own behavioral research needs. Most importantly, a working knowledge of MATLAB will allow you to perform some analyses that would be tedious, difficult, or impossible otherwise. In addition, you will be able to understand and build upon the work of colleagues who use MATLAB in their work. You will probably find this book most useful if you use it in two stages. In the first, you will want to go through it, or the parts of it most relevant to your needs, in considerable detail, working problems and developing the hands-on skills that will make you a MATLAB user , not just a MATLAB appreciator . In the second stage, you will be able to rely on the book as a reference, turning quickly to those sections that provide examples you can adapt for your own programming needs. To make the book as useful as possible as a reference source, we have designed it so you can get the examples you need quickly and easily. You can do so by turning to the opening page of any chapter and finding there a list of things you may want to do. Beneath that list is a compendium of associated commands. The text itself provides examples you can adapt for your own purposes. You can copy those examples by hand into your own programs, or, to avoid typographical errors, you can copy and paste them from the website associated with this book ( www.routledge.com/9780415535946 ), where the programs and their outputs are available, along with the solution to selected problems. Finally, the list of commands introduced in each chapter is listed as well in the Commands Index. 1.2 Getting an Overview of This Book Acquiring a new skill such as computer programming can be daunting, so it helps to have an overview of what you can expect as you proceed. Here, then, is a roadmap of the contents of this book. Besides signposts, we also provide brief explanations of the goals of each chapter. 1. Introduction. By reading the present chapter, you will learn more than you may already know about how computers work and what computer programming languages do. You will also learn about the ways you should approach computer programming. Finally, by reading this chapter, you will understand how this book is organized. That information can help you use the book efficiently. 2. Interacting With MATLAB. By delving into the second chapter, you will learn how to activate MATLABÊs windows in order to open, edit, save, and run MATLAB programs
Introduction 3 、data.Brie sy Matri data nd o me of the la or more io a ally shor 'Matrix Lab You can think of a t having both ow and colu analogous to the rows and columns ina spreadsheet 4.Calculations.Computers are good at calculating.Chapter 4 shows how to get your computer to carry out calculations with MATLAB. 5.Contingencies.One of the main purposes of a computer program is to perform dif- ferent actions depending on existing conditions.The logic of a program involves not only calculations but also decision making.such as evaluating variables differently (or not evaluating them at all),depending on their values. 6.Input-Output.Chapter 6 shows you how to control your computer's interactions with the external world.By studying Chapter 6.you will be able to design programs that let you create dialogs with users,including participants in behavioral studies. and to read and write data to and from external files. 7.Data Types.One of the biggest challenges in using computers in research is deter mining how best to represent the data you are working with.It is important to under yourttybl in MALA you can choose and manipulac 8. Modules and Functions.Simple prog ms are usu ly easy to understand,but they b re,compl pful s.S me higl ws y e modu d func ctive.Modules and func 9.Plots.The ability to generate and manipulate complex graphics for the exploratior and presentation of data is widely regarded as one of the special strengths of MAT- LAB.Chapter 9 exposes you to those strengths by showin you how to make line graphs,bar graphs,and other types of graphs that are suitable for professional pre- sentations and publications. 10.Lines,Shapes,and Images.Here you will learn how to create,import,or reshape lines,shapes,and other images that can either stand alone or be included in graphs. Chapter 10 will also show you how to generate three-dimensional graphs. 11.Animation and Sound.Chapter 11 builds on the static graphics of the tenth chapter to manipulate figures using simple animation techniques,generate movies,and gen- erate auditory stimuli 12.Enhanced User Inte wha to mind ally througl graphic the k some
Introduction 3 3. Matrices. By studying the third chapter, you will learn how MATLAB enables you to store and access data. Briefly, MATLAB lets you store data in matrices consisting of one or more rows and one or more columns. Matrices are so fundamental to MATLAB that the name of the language is actually short for „Matrix Laboratory.‰ You can think of a two-dimensional matrix (one having both rows and columns) as analogous to the rows and columns in a spreadsheet. 4. Calculations. Computers are good at calculating. Chapter 4 shows how to get your computer to carry out calculations with MATLAB. 5. Contingencies. One of the main purposes of a computer program is to perform different actions depending on existing conditions. The logic of a program involves not only calculations but also decision making, such as evaluating variables differently (or not evaluating them at all), depending on their values. 6. Input-Output. Chapter 6 shows you how to control your computerÊs interactions with the external world. By studying Chapter 6, you will be able to design programs that let you create dialogs with users, including participants in behavioral studies, and to read and write data to and from external files. 7. Data Types. One of the biggest challenges in using computers in research is determining how best to represent the data you are working with. It is important to understand what data types are available in MATLAB so you can choose and manipulate your data types accordingly. 8. Modules and Functions. Simple programs are usually easy to understand, but when they become more complex it often helps to deal with them in chunks. Some higher level structure is often helpful. Chapter 8 shows you how to write programs that have this property. Those programs often have stand-alone modules and functions. Such modules and functions can be called by a variety of programs. Using modules and functions can help you approach programming from a top-down rather than a bottom-up perspective. Modules and functions can also facilitate the reuse of programs in the future. 9. Plots. The ability to generate and manipulate complex graphics for the exploration and presentation of data is widely regarded as one of the special strengths of MATLAB. Chapter 9 exposes you to those strengths by showing you how to make line graphs, bar graphs, and other types of graphs that are suitable for professional presentations and publications. 10. Lines, Shapes, and Images. Here you will learn how to create, import, or reshape lines, shapes, and other images that can either stand alone or be included in graphs. Chapter 10 will also show you how to generate three-dimensional graphs. 11. Animation and Sound. Chapter 11 builds on the static graphics of the tenth chapter to manipulate figures using simple animation techniques, generate movies, and generate auditory stimuli. 12. Enhanced User Interaction. When you think of a typical computer application, what comes to mind is how the program interacts with the user, typically through graphics, the keyboard, the mouse, or touchscreen. Chapter 12 introduces you to some of the tools available in MATLAB for user interactions
4 Introduction 13.Psychtoolbox.For real-time work,there are some features that MATLAB ordi- narily lacks that are needed for precise and flexible stimulus presentation and data acquisition.Chapter 13 describes a sophisticated extension to MATLAB,Psychtool box.which adds features to facilitate research using MATLAB.especially in vision research.This chapter also touches on related packages of interest to behavioral sci entists in related areas. 14.Debugging.Programs often have bugs because,for better or worse,programming is often a tria and-error procetowto addre every poss r own,to These are ther h MATLAB.T ovides pointers for going fur draw on A lot of material will be cov vered in this book. rough all of it?If have no ne ed to play sound or gen S0 al graphic you may safe rge parts o ugh 1 fing thr 11 y ast if dy Alle ed fr m his s eed-reading of Tols epic novel,War and Peace."I was about Russia" The truly essential chapters of this book are Chapters 2 through 5.You cannot go on to the later chanters and exneet to have control of your ograms if you don't have command of the material in cha ers2 through 5.and the only way to gain that command is to work your way through the examples and exercises slowly and carefully.We promise that even if you think you understand how things work,the only way to be sure is to try them out and expose yourself to the feedback you will receive. As you gain expertise,Chapters 6 through 8 will allow you to write more sophisticated code.Chapters 9 through 13 will provide you with specialized tools for your work and enjoyment.And Chapter 14,as already mentioned,will suggest ways to help you debug efficiently. A word of advice:Don't hesitate to revisit earlier sections of the book as you move through it.No one remembers perfectly,and no one understands material quite as fully the first time as in revi ling of what may seem very obscure the R r un derstand t time throug 1.3 Understanding Computer Architecture
4 Introduction 13. Psychtoolbox. For real-time work, there are some features that MATLAB ordinarily lacks that are needed for precise and flexible stimulus presentation and data acquisition. Chapter 13 describes a sophisticated extension to MATLAB, Psychtoolbox , which adds features to facilitate research using MATLAB, especially in vision research. This chapter also touches on related packages of interest to behavioral scientists in related areas. 14. Debugging. Programs often have bugs because, for better or worse, programming is often a trial-and-error process. While it is hard to know in advance how to address every possible bug, it is possible, based on the authorsÊ many goofs of their own, to convey advice about debugging techniques which you may find useful. These are offered in Chapter 13 . . . oops, Chapter 14 (). 15. Going On. Chapter 15, the last chapter of the book, provides pointers for going further with MATLAB. This chapter also directs you to other resources you may want to draw on. A lot of material will be covered in this book. Do you need to go through all of it? If you have no need to play sounds, show animations, or generate three-dimensional graphics, you may safely ignore large parts of Chapters 9 through 13, though leafing through these chapters may help you overcome any prejudices or fears you might have regarding these topics. At the same time, there are chapters you cannot avoid, at least if you donÊt want to emerge from this book the way Woody Allen emerged from his speed-reading of TolstoyÊs epic novel, War and Peace . „It was about Russia‰ was all he could recall. The truly essential chapters of this book are Chapters 2 through 5. You cannot go on to the later chapters and expect to have control of your programs if you donÊt have command of the material in Chapters 2 through 5, and the only way to gain that command is to work your way through the examples and exercises slowly and carefully. We promise that even if you think you understand how things work, the only way to be sure is to try them out and expose yourself to the feedback you will receive. As you gain expertise, Chapters 6 through 8 will allow you to write more sophisticated code. Chapters 9 through 13 will provide you with specialized tools for your work and enjoyment. And Chapter 14, as already mentioned, will suggest ways to help you debug efficiently. A word of advice: DonÊt hesitate to revisit earlier sections of the book as you move through it. No one remembers perfectly, and no one understands material quite as fully the first time as in revisits. Your understanding of what may seem very obscure the first time through will be enhanced by the top-down knowledge and context you will acquire touring later material. 1.3 Understanding Computer Architecture As a first step toward learning to program, it can be helpful to know a bit about computer architecture. Knowing about the main components of a computer can help you understand what features of the environment your program must deal with
Introduction 5 All working computers have five basic in Figure 13.1.these are and video and voltas ers that are useful in thea YE(2)S etc )(3) vices (hard disks and (5)the sing The first three c ents should need no further explanation.The last two comp merit more discussion. Central Memory Unit Storage Figure1.3.1 Primary memory (item 4 on the list)is like human or animal working memory.Its contents are currently active information.The amount of information that can be kept in this active state is limited,both in biological agents(humans and animals)and in computers.The amount of information a computer can maintain in primary memory is hardware dependent. Because the capacity of primary memory is limited,it is important to be mindful of the The amount of informatior mac written in MATLAB.depends on th e numbe ared and the number of bits(the number of Is and 0s)required to ed; larger tha nount eded Wewi Chapiter 7(Data Types) Returning to the co nents of comn ter architecture.the fifth c ent is the central processing unit.This is the part of the om puter that executes instructions.For pr ent oses.the central unit or can he likened to c ess,for which d.onl one thou dam 190.The same an be said of computer's CPU.It can handle only one instruction at a time.at least in a conventional digi- tal computer.Handling just one instruction at a time is called serial processing.Handling more than one instruction at a time is called parallel processing. Serial processing can occur at high rates in modern computers.For example,the computer on which this text was prepared (a Dell laptop)runs at 2 gigahertz(2 billion cycles per second)
Introduction 5 All working computers have five basic elements. As shown in Figure 1.3.1 , these are (1) input devices (not only the conventional keyboards and mice, but also the microphones, response buttons, and video and voltage recorders that are useful in the laboratory); (2) output devices (screens, printers, loudspeakers, etc.); (3) storage devices (hard disks, thumb drives, DVDs, the „Cloud,‰ etc.); (4) primary memory; and (5) the central processing unit. The first three components should need no further explanation. The last two components merit more discussion. Figure 1.3.1 Primary memory (item 4 on the list) is like human or animal working memory. Its contents are currently active information. The amount of information that can be kept in this active state is limited, both in biological agents (humans and animals) and in computers. The amount of information a computer can maintain in primary memory is hardware dependent. Because the capacity of primary memory is limited, it is important to be mindful of the amount of information a computer can keep active at once. The amount of information made active by a program, such as one written in MATLAB, depends on the number of variables that are declared and the number of bits (the number of 1s and 0s) required to represent each variable. Essentially, there are three ways of using primary memory efficiently: (1) defining just the variables that are needed; (2) clearing variables once they are no longer needed; and (3) defining the types of the variables so the amount of memory initially reserved for them is large enough but not substantially larger than needed. We will return to these topics in Chapter 7 („Data Types‰). Returning to the components of computer architecture, the fifth component is the central processing unit. This is the part of the computer that executes instructions. For present purposes, the central processing unit, or CPU, can be likened to consciousness, for which, it is said, only one thought can exist at a time (James, 1890). The same can be said of a computerÊs CPU. It can handle only one instruction at a time, at least in a conventional digital computer. Handling just one instruction at a time is called serial processing. Handling more than one instruction at a time is called parallel processing. Serial processing can occur at high rates in modern computers. For example, the computer on which this text was prepared (a Dell laptop) runs at 2 gigahertz (2 billion cycles per second)
6 Introduction Regardless of the speed at which a CPU runs,serial processing imposes constraints on the kinds of programs you can run,and therefore write,in MATLAB.Suppose,for example. that you want to find the largest value among a set of numbers.Parallel processing is a natural way to solve this problem.If the values are plotted as in Figure 1.3.2.for example. a brief glance at the bars lets you pick the biggest one.The tallest bar seems to jump out at you.Once it does,you can look down to find the associated element (element 3 in this case).or you can look to the left to find the largest value (39 in this case). Figure1.3.2 You might object that parallel evaluation of the heights of all the bars in this case is not actually possible,and even it were for this particular figure,it wouldn't be for all other sets of numbers.such as those whose largest values are similar.You might also say that the method outlined above is not a truly parallel process because distinct stages are associated with looking down the tallest bar or looking sidewise from the top of the tallest bar.These objections are well taken,especially considering that serial processing is inescapable in tep at a time (serially) Knowing this can help you approach the task of programming.(Many recent computers calake ae procorrh mke para om poea f these to speed compl ng tw things at once,using computations e t your programming skills with this book.yey save paralle 1.4 Programming Principles How should you approach the task of programming?We have come to believe in the fol lowing principle .Decide if a program is actually needed and,if so.whether you should write it .Be as clear as possible about what your program should do
6 Introduction Regardless of the speed at which a CPU runs, serial processing imposes constraints on the kinds of programs you can run, and therefore write, in MATLAB. Suppose, for example, that you want to find the largest value among a set of numbers. Parallel processing is a natural way to solve this problem. If the values are plotted as in Figure 1.3.2 , for example, a brief glance at the bars lets you pick the biggest one. The tallest bar seems to jump out at you. Once it does, you can look down to find the associated element (element 3 in this case), or you can look to the left to find the largest value (39 in this case). Figure 1.3.2 You might object that parallel evaluation of the heights of all the bars in this case is not actually possible, and even it were for this particular figure, it wouldnÊt be for all other sets of numbers, such as those whose largest values are similar. You might also say that the method outlined above is not a truly parallel process because distinct stages are associated with looking down the tallest bar or looking sidewise from the top of the tallest bar. These objections are well taken, especially considering that serial processing is inescapable in MATLAB, at least in a program that uses MATLAB in its usual configuration. To sort values or do anything else in MATLAB, everything must be done one step at a time (serially). Knowing this can help you approach the task of programming. (Many recent computers have multiple processors, or cores , that make parallel computing possible. Advanced users can take advantage of these to speed complex computations by having two or more cores compute different things at once, using additional tools available from The MathWorks. If you are beginning your programming skills with this book, you can safely save parallel programming for another time.) 1.4 Programming Principles How should you approach the task of programming? We have come to believe in the following principles: Ć Decide if a program is actually needed and, if so, whether you should write it. Ć Be as clear as possible about what your program should do