Introduction 17 given by If the i-th value of theDataArray is greater than_th valne of theDataarray After having gone through the whole array,print out 8largest so far,which will be the largest value found, theDataArray=[73339268181540]; &start with an absurdly small maximum largest_so_far =-inf; for i =1:length(theDataArray) if theDataArray(i)>largest_so_far 号Got a new candidate! largest so far theDataArray(i); end end 8All done. Output 1.11.2: largest_of_them_all 39 1.12 Writing Correct Programs If your program does not generate any error messages and generates plausible output,does that mean the results are correct?You will find that the MATLAB programming environ- ment,introduced in Chapter 2.serves as an excellent source of feedback as you write and then try to run your own programs.You will be told,indirectly or directly,if your syntax (word use and punctuation)is acceptable or unacceptable.If your syntax is unacceptable you will get an error mes sage.Otherwise,your program will run.If you get an errorr sage,it will be up to you to figure out what needs to be done to re ve the error.It takes some time to leam to interpret error messages,but over time you will learn to do so If your syntax is acceptable.it is your responsibility to confirm that the output you one does ging A your program's what y rk.but lurking within it i btle Detecting such mistakes is one of the most challenging aspects of programming.In ger eral.dev m that works ore than an understandin f programming syntax.Italso requres greater clarity and about procedures to
Introduction 17 % to the number of elements of theDataArray, given by % length(theDataArray). % If the i-th value of theDataArray is greater than % largest_so_far,reassign largest_so_far with the i-th % value of theDataArray. % After having gone through the whole array, print out % largest_so_far, which will be the largest value found. theDataArray = [7 33 39 26 8 18 15 4 0]; %start with an absurdly small maximum largest_so_far = -inf; for i = 1:length(theDataArray) if theDataArray(i) > largest_so_far %Got a new candidate! largest_so_far = theDataArray(i); end end % All done. . .so what's the maximum? largest_of_them_all = largest_so_far Output 1.11.2: largest_of_them_all = 39 1.12 Writing Correct Programs If your program does not generate any error messages and generates plausible output, does that mean the results are correct? You will find that the MATLAB programming environment, introduced in Chapter 2, serves as an excellent source of feedback as you write and then try to run your own programs. You will be told, indirectly or directly, if your syntax (word use and punctuation) is acceptable or unacceptable. If your syntax is unacceptable, you will get an error message. Otherwise, your program will run. If you get an error message, it will be up to you to figure out what needs to be done to resolve the error. It takes some time to learn to interpret error messages, but over time you will learn to do so. If your syntax is acceptable, it is your responsibility to confirm that the output you get is correct, because correct syntax alone does not guarantee correct program logic. You will find that judging the correctness of your programÊs output is often as challenging as generating acceptable syntax. As in natural language, an expression can be syntactically correct but not mean what you intend. Sometimes a program seems to work, but lurking within it is some subtle error that makes the output obviously wrong or, much worse, seemingly correct but actually flawed. Detecting such mistakes is one of the most challenging aspects of programming. In general, developing a program that works correctly requires more than an understanding of programming syntax. It also requires greater clarity and explicitness about procedures to
18 Introduction be followed than is usually required in daily life.Additionally,it requires some way of veri- fying the output.Striving for such clarity and explicitness is one of the things that makes programming a humbling.though educational,experience. As you plan your program,pay attention to the eventual means of verification as well as the logic of computation.For instance,suppose you have a set of reaction-time data from a within-subjects design experiment.In such a design,the number of trials observed in each condition may be determined by the experimental design.Part of the output of the analysis program that you write can be the number of trials in each condition(ntrials)for each ubject,even r th values d)values You can take getting ce t at a als have been con anoma y in the value ials may alert you to an error somewhere,whethe summary computatio Relatedly,if a program alyzes the data of dozer s,it is well worth pe the two part ible yn.In fas one subject by hand insights best to app ach the ning by min it's no a had idea to have tw ch inde ram to ame data.if the ty ere're in every detail ou can he reasonabl o i the correctess of the analysis.If it ts out that there is some detail in which the two results do not agree,that outcome provides an opportunity to explore the difference to see if it is due to a programming eor,a difference in under standing the data,or error(s)in the analysis logic Another useful shortcut for data verification is to exploit a different analysis environment to serve as that"second programmer."The results of analyzing a small subset of the data in a spreadsheet or statistical package should agree perfectly with the corresponding output of your MATLAB program.If the results differ.even apparently trivially.you will want to track down the source of the disagreement. 1.13 Understanding How the Chapters of This Book Are Organized If you are persuaded that it makes sense for you to go further with this book,it will help you to understand how the book's chapters are organized ers the following topics.after which those subjects are I entation of the chapters section names.All the section names of this book begin with gerunc such as"Understand g·· Appro The sec sare titled this way because we eam by doing.You i ng.approaching. ddeciding (to name some activities)as you pursue the material presented here all the sectio pre ed ar ”This edes a list of all the ds int ith the rst dis you run you the list and find the o which it nds,you should
18 Introduction be followed than is usually required in daily life. Additionally, it requires some way of verifying the output. Striving for such clarity and explicitness is one of the things that makes programming a humbling, though educational, experience. As you plan your program, pay attention to the eventual means of verification as well as the logic of computation. For instance, suppose you have a set of reaction-time data from a within-subjects design experiment. In such a design, the number of trials observed in each condition may be determined by the experimental design. Part of the output of the analysis program that you write can be the number of trials in each condition ( n_trials ) for each subject, even if those values do not enter into subsequent analyses. You can take getting the correct (i.e., predicted) values of n_trials in each condition as evidence that all trials have been considered in the analysis. Conversely, any apparent anomaly in the values of n_trials may alert you to an error somewhere, whether in data acquisition or in the summary computation. Relatedly, if a program analyzes the data of dozens of participants, it is well worth performing the analysis of at least one or two participants by hand, if possible, to verify the match between the computerÊs computations and your own. In fact, beginning by doing one subject by hand will give you insights into how best to approach the programming problem. Similarly, itÊs not a bad idea to have two researchers each independently write a program to analyze the same data. If the two programmersÊ results agree in every detail, you can be reasonably confident in the correctness of the analysis. If it turns out that there is some detail in which the two results do not agree, that outcome provides an opportunity to explore the difference to see if it is due to a programming error, a difference in understanding the data, or error(s) in the analysis logic. Another useful shortcut for data verification is to exploit a different analysis environment to serve as that „second programmer.‰ The results of analyzing a small subset of the data in a spreadsheet or statistical package should agree perfectly with the corresponding output of your MATLAB program. If the results differ, even apparently trivially, you will want to track down the source of the disagreement. 1.13 Understanding How the Chapters of This Book Are Organized If you are persuaded that it makes sense for you to go further with this book, it will help you to understand how the bookÊs chapters are organized. Each chapter begins with the sentence, „This chapter covers the following topics,‰ after which those subjects are listed. The way the subjects are listed is via presentation of the chaptersÊ section names. All the section names of this book begin with gerunds, such as „Understanding . . . ,‰ „Approaching . . . ,‰, or „Deciding . . . .‰ The sections are titled this way because we want you to learn by doing. You should be actively engaged in understanding, approaching, and deciding (to name some activities) as you pursue the material presented here. Continuing with the layout of the chapters, after all the section titles are given, each chapter continues with the sentence, „The commands that are introduced and the sections in which they are premiered are:.‰ This sentence precedes a list of all the new commands introduced in the chapter, along with the sections in which those new command are first discussed. If you run your finger down the list and find the activity to which it corresponds, you should
Introduction 19 alpha tically.with reference to thei Every program shown in this book has a code number.The first number(to the left of the ars.The second number (between the two decimal points)co onds to the s which the code ears.Th section.All MATLAB code ap pears in Courier font,as do all words taken from the code shown in the text body of this book. Every program that yields output has its output shown in the same format as the code.The output has a number that corresponds to the code that produced it. One thing that is missing from the programs shown in this book are extensive comments. We have left them out not because comments are unimportant but because,for most of the programs in this book,the comments are,in effect,presented in the text leading up to the programs.If you imagine percent signs in front of the lines of text preceding the code for a program shown here.you effectively have the kind of comment that can be supplied in a program. Does it make sense for you to read the code shown in this book?Shouldn't you just dive ng or sv ming as the ase may be?We c on't want you to sinl you to sw we d by re You can learn can be one of the w it does an al ys ed e or she reads i 1.14 Using the Website Associated With This Book As you leaf through this book,you will see that all the graphs and images are in grayscale. The programs that yield these graphs and images allow for color graphics.The reason the book has grayscale images is to keep the cost of production down,which translates into a lower price for you.You can see the color images generated by the programs,and animations. by going to the website associated with this book(www.routledge.com/9780415535946). You will be able to copy the programs and outputs as you wish 1.15 Obtaining and Installing MATLAB How can you access MATLAB?You or your institution can purchase individual or shared licenses.Students can also purchase the educational version for their own use. MATLAB is,formally.a cross-platform programming environment with versions for Win- dows,Mac OS,and Unix.There are superficial differences between the Windows version of MATLAB and the version that runs under the Mac OS or Unix operating system.If a eethe rom
Introduction 19 be able to turn to that section and find an example of how the command is used. The commands discussed are also listed alphabetically, with reference to their first mention, in the Commands Index. Every program shown in this book has a code number. The first number (to the left of the decimal point) corresponds to the chapter in which the code appears. The second number (between the two decimal points) corresponds to the section in which the code appears. The third number (to the right of the second decimal point) is the number of the code within the section. All MATLAB code appears in Courier font, as do all words taken from the code shown in the text body of this book. Every program that yields output has its output shown in the same format as the code. The output has a number that corresponds to the code that produced it. One thing that is missing from the programs shown in this book are extensive comments. We have left them out not because comments are unimportant but because, for most of the programs in this book, the comments are, in effect, presented in the text leading up to the programs. If you imagine percent signs in front of the lines of text preceding the code for a program shown here, you effectively have the kind of comment that can be supplied in a program. Does it make sense for you to read the code shown in this book? ShouldnÊt you just dive in code for yourself, sinking or swimming as the case may be? We donÊt want you to sink. We want you to swim, and we think there is much to be learned by reading successful code to figure out what it does and how it does it. You can learn by example. Starting with examples of code can be one of the best ways to learn to program. You can always edit the working example for your own needs, much as a cook can edit a recipe he or she reads in a cookbook. 1.14 Using the Website Associated With This Book As you leaf through this book, you will see that all the graphs and images are in grayscale. The programs that yield these graphs and images allow for color graphics. The reason the book has grayscale images is to keep the cost of production down, which translates into a lower price for you. You can see the color images generated by the programs, and animations, by going to the website associated with this book ( www.routledge.com/9780415535946 ). You will be able to copy the programs and outputs as you wish. 1.15 Obtaining and Installing MATLAB How can you access MATLAB? You or your institution can purchase individual or shared licenses. Students can also purchase the educational version for their own use. MATLAB is, formally, a cross-platform programming environment with versions for Windows, Mac OS, and Unix. There are superficial differences between the Windows version of MATLAB and the version that runs under the Mac OS or Unix operating system. If a program involves certain kinds of input-output, there may be differences across platforms, but these will not interfere with your mastery of the basics of the language
20 Introduction The differences between the Windows and Mac OS platforms relate primarily to common platform-specific GUI(graphical user interface)conventions and aspects of interfacing for real-time data acquisition.Most of the computational features of MATLAB are equivalent across platforms.so programs written on one platform should work on another.Where there are important platform differences that can cause problems,we will point them out, though we cannot anticipate all problems that might arise. As of this writing.we have used versions MATLAB installed in the following contexts: .As a stand-alone program,y to a particular researcher under an .Under an educational site license in which the number of simultaneous userson a campus nitored by a local serve imrey on a centra srver,fo which a limited number of )that allows the running of much of the code of MATLAB.OCTAVE lacks the closely coordinated debugg ing and p most of the computational operations of MATLAB. The examples in this text should almost all run identically regardless of the environment and MATLAB version("release")that is used.For the most part,we have relied on the current Windows release.R2013a.released March 1.2013.Because successive MATLAB releases are upward compatible (later versions are compatible with earlier versions),what you learn here should apply to later releases. How should MATLAB be installed?It is outside our scope to describe the installation pro cedures needed to get MATLAB to run wherever you are,in part because the details vary e type of licesou hol Lersion you are using.the plattorm you are running MArd cal knowledge A on ass Section 2. ided you have your license number handy:see thever command in Chapter 2. 1.16 Acknowledging Limits The final section of this chap ok" pter is mportant fo yhor TLAB so you we First with
20 Introduction The differences between the Windows and Mac OS platforms relate primarily to common platform-specific GUI (graphical user interface) conventions and aspects of interfacing for real-time data acquisition. Most of the computational features of MATLAB are equivalent across platforms, so programs written on one platform should work on another. Where there are important platform differences that can cause problems, we will point them out, though we cannot anticipate all problems that might arise. As of this writing, we have used versions MATLAB installed in the following contexts: Ć As a stand-alone program, individually licensed to a particular researcher under an academic license. Ć As a stand-alone program (student version), individually licensed to an undergraduate or graduate student. Ć Under an educational site license in which the number of simultaneous users on a campus is monitored by a local server. Ć As a program that runs remotely on a central server, to which a limited number of simultaneous users may log on. Ć Using an open-source alternative to MATLAB, called OCTAVE ( www.gnu.org/soft ware/octave/ ), that allows the running of much of the code of MATLAB. OCTAVE lacks the closely coordinated debugging and program management tools of MATLAB, and we have found that its graphics are less sophisticated, but it is capable of most of the computational operations of MATLAB. The examples in this text should almost all run identically regardless of the environment and MATLAB version („release‰) that is used. For the most part, we have relied on the current Windows release, R2013a, released March 1, 2013. Because successive MATLAB releases are upward compatible (later versions are compatible with earlier versions), what you learn here should apply to later releases. How should MATLAB be installed? It is outside our scope to describe the installation procedures needed to get MATLAB to run wherever you are, in part because the details vary depending on the version you are using, the platform you are running on, and the type of license you hold. Ideally, you will have local knowledge to draw on, but MATLAB support through The MathWorks, Inc., is typically very responsive to calls for installation assistance, provided you have your license number handy; see the ver command in Chapter 2, Section 2.2. 1.16 Acknowledging Limits The final section of this chapter is concerned with the limits of this book, our limits as the bookÊs authors, and the limits of MATLAB itself. It is important for you to know what these limits are so you wonÊt form unrealistic expectations. First, with regard to the book, you should know that you will not be able to program in MATLAB if you just read this book without also trying to program yourself. Reading how
Introduction21 yourself ples in this book e had to les of the rskills then if you ha You should also know that the material presented in this book is meant to acquaint you with maTlab but not to convey everv aspect of this vast language and its associated applications.This book would be much denser if it went into many more detailed and advanced aspects of the MATLAB programming language.You should be able to delve into these topics on your own having worked through the material provided here. Third,you should know about the limits of MATLAB.The"word on the street"is that MATLAB is terrific for graphics and for creating conceptual models.Its reputation is less secure when it comes to real-time data gathering,where commercial or free alternatives like E-Prime,PsyScope,and SuperLab are often favored.For large-scale number crunch- ing or statistics,C/C++,R,SPSS,or SAS may be better than MATLAB.On the other hand MATLAB is being actively enhanced in so many quarters that its limitations,whatever they may be.will probably wane over time as needed tools are being developed to address deficiencies that are spotted by the MATLAB community. can be mentioned here.One is Psychtoolb cussed i controli hich e MATLAB C r (not e converte ha one can le bout the and othe oxes prov baor ling).the p ram exa s are not drawn from a particular a oach or finding.The interests of behavioral scientists are.so her rather than specific.They are selected more to highlight particular features of MATLAB than to address specific scientific questions
Introduction 21 to program is a little like reading how to ride a bike. You have to get on and try it yourself. DonÊt worry if you fall off a few times. Indeed, experienced as we authors may be, in preparing the examples in this book we had to spend quite a bit of time getting the syntax to work just right, often with many cycles of the edit-run-error-edit loop. ItÊs no reflection on your skills, then, if you have lots of false starts when putting together a new programming project. We, the authors of this book, have gone through those false starts ourselves. You should also know that the material presented in this book is meant to acquaint you with MATLAB but not to convey every aspect of this vast language and its associated applications. This book would be much denser if it went into many more detailed and advanced aspects of the MATLAB programming language. You should be able to delve into these topics on your own having worked through the material provided here. Third, you should know about the limits of MATLAB. The „word on the street‰ is that MATLAB is terrific for graphics and for creating conceptual models. Its reputation is less secure when it comes to real-time data gathering, where commercial or free alternatives like E-Prime, PsyScope, and SuperLab are often favored. For large-scale number crunching or statistics, C/C++, R, SPSS, or SAS may be better than MATLAB. On the other hand, MATLAB is being actively enhanced in so many quarters that its limitations, whatever they may be, will probably wane over time as needed tools are being developed to address deficiencies that are spotted by the MATLAB community. Three examples of such tools can be mentioned here. One is Psychtoolbox (discussed in Chapter 13), which has methods for precise real-time control in psychophysical research. Another tool is an add-on toolbox, MATLAB Coder (not discussed further in this book), which enables MATLAB programs to be converted and distributed as C++ code. A third toolbox from The MathWorks, Parallel Computing, enables intensive computation to be distributed across multiple processors if your computer has more than one. You can learn more about these and other toolboxes provided by The MathWorks by going to their website. Another comment about the limits of the book is that while the program examples presented here should be comprehensible to you as a behavioral scientist (veteran or fledgling), the program examples are not drawn from a particular approach or finding. The interests of behavioral scientists are highly varied, so the examples offered here are generic rather than specific. They are selected more to highlight particular features of MATLAB than to address specific scientific questions