MATLAB For Behavioral Scientists 2nd Edition No-Wait Download
MATLAB For Behavioral Scientists 2nd Edition No-Wait Download
Visit the link below to download the full version of this book:
https://medipdf.com/product/matlab-for-behavioral-scientists-2nd-edition/
Second Edition
David A. Rosenbaum,
Jonathan Vaughan, and Brad Wyble
MATLAB® is a trademark of The MathWorks, Inc. and is used with permission.
The MathWorks does not warrant the accuracy of the text or exercises in this
book. This bookÊs use or discussion of MATLAB® software or related products
does not constitute endorsement or sponsorship by The MathWorks of a particular
pedagogical approach or particular use of the MATLAB® software.
% Dedication.m
clc
for author = {'Brad' 'Jon' 'David'}
authorstring = char(author);
switch authorstring
case 'Brad'
Dedication.to = 'Elizabeth Spillman-Wyble';
Dedication.features = ...
{'inspiration','storytelling',...
'mastery of folklore',...
'extraordinary cooking'};
case 'Jon'
Dedication.to = 'Virginia Vaughan';
Dedication.features = ...
{'intelligence','strength of character',...
'unfailing support','generosity'};
case 'David'
Dedication.to = 'Judith Kroll';
Dedication.features = ...
{'brilliance', 'bravery', 'beauty'};
end
fprintf('%s dedicates this work to %s',...
authorstring,Dedication.to);
fprintf(' in grateful recognition of her ');
for featurecount = 1:length(Dedication.features)-1
fprintf('%s, ',...
Dedication.features{featurecount});
end
fprintf('and %s.\n\n',Dedication.features{end})
end
commandwindow
Dedication Output
Preface ix
Acknowledgements xii
1 Introduction 1
3 Matrices 38
4 Calculations 62
5 Contingencies 99
6 Input-Output 128
9 Plots 208
13 Psychtoolbox 323
14 Debugging 355
15 Going On 370
vii
viii Contents
References 375
The first edition of MATLAB for Behavioral Scientists (published in 2007) was the result
of a rebellious thought. The prevailing view before then was that most behavioral scientists
shouldnÊt or couldnÊt write their own computer programs. This irked the first author, who
decided to pursue the notion that all behavioral scientists, including students in the relevant
fields (psychology, cognitive and affective neuroscience, economics, and so on), could and
should learn to program for themselves.
Behavioral scientists need to be able to program as much as scientists in other fields. They
need to be able to program to do whatever they want, computationally speaking, without
having to rely on the kindness of strangers or the largesse of granting agencies to pay others
to program for them.
To give some examples, a behavioral scientist·a behavioral economist, say·wishing
to model decision making should be able to roll up her sleeves and graph data showing
observed and expected data in the way she prefers. A personality psychologist interested
in designing a new questionnaire requiring a special computer interface should be able to
pursue that aim. A psychotherapist wanting to model changing relations between mem-
bers of a family should be able to characterize that process with custom-made animations
that show network links with dynamically changing thicknesses and colors, growing and
shrinking over time, if thatÊs what she wants. A cognitive psychologist interested in setting
up and conducting behavioral experiments should be able to create any kind of stimuli and
response recording capabilities he or she cares to, not being limited by whatÊs possible with
off-the-shelf commercial products.
This book is meant to help behavioral scientists (and especially students entering this field)
to do these things. The authors of this book assume you have no prior familiarity with com-
puter programming, and we assume you have no knowledge of mathematics beyond what
is generally learned in high school. The text is meant to be as friendly and encouraging as
possible. Our aim is to draw you in and help you feel comfortable within a domain that may
at first seem foreign and maybe even scary.
Programming can be humbling. If you set out to learn to program, you should prepare your-
self emotionally as well as intellectually for what will happen because you will be dealing
with an unfeeling machine. It takes a tough hide to believe you have a program that does
what you want, only to discover that the program doesnÊt run, generates unexpected results,
or produces outputs that seem reasonable at first but then turn out to be wrong. Everyone
who has programmed has gone through this, including the authors of this book, so donÊt
feel like you need to be able to program perfectly. No one does!
Programming neednÊt be unpleasant, however. The attitude to have is to keep an open
mind about the value of mistakes. If you treat errors as windows for improvement, you will
learn a lot. Availing yourself of that learning, when you see a program work and especially
ix
x Preface
when it does something that, to your knowledge, has not been done before, can let you feel
rightly proud of your achievement.
There are many computer programming languages. Why is this book about MATLAB?
MATLAB (short for Matrix Laboratory), is a commercial product of a company called The
MathWorks (Natick, Massachusetts), for which we authors do not work and have no com-
mercial connection. The following, therefore, can be taken as our honest opinion of their
product: MATLAB is a simple yet powerful language for computer programming. It has
an active community of users, engaged in many branches of science and engineering. One
of MATLABÊs most attractive features is that it offers high-level commands for perform-
ing calculations with large as well as small data sets and for generating publication-quality
graphics. Another attraction of MATLAB is that it allows for the presentation of stimuli
and the collection of responses with precise timing. Yet another attraction is that MATLAB
is platform-independent. It runs on PCs, Macs, and Linux machines. For these and other
reasons, MATLAB is a very good language for behavioral scientists. A growing number
of behavioral scientists, along with neuroscientists, engineers, and investigators in other
disciplines, have therefore chosen to learn MATLAB. Owing to the health and vitality of
the MATLAB programming community, it is likely that more and more people will want
to learn MATLAB in the future. You will be part of that active community if you choose to
dive into the material provided here.
How did it come to pass that there is a second edition of this book? As is always true of a
second edition, its predecessor was successful enough to keep the work alive, but changes
in the field suggested a face-lift was needed. Among the needed changes was the appear-
ance of other MATLAB books for psychologists and neuroscientists (Fine & Boynton,
2013; Madan, 2014; Wallisch et al., 2009), which are welcome additions, though they are
different in style, tone, level of coverage, and organization from the first edition of this
book (but not so perfect, in our view, that they obviate this second edition).
As the author of the first edition (Rosenbaum, 2007) contemplated the second edition, he
realized that the process of revising and updating the book would benefit from the involve-
ment of his long-time friend and collaborator, Jonathan Vaughan, the James L. Ferguson
Professor of Psychology and Neuroscience at Hamilton College. Jon has decades of experi-
ence with computer programming. He has served as the editor of Behavior Research Meth-
ods, Instruments, & Computers, a peer-reviewed publication of the Psychonomic Society.
The first author basically learned MATLAB from Jon. He continued to learn from Jon in
preparing this second edition.
When Jon agreed to join in, he and David began to map out the ways the second edi-
tion would differ from the first. Among the things they agreed to were the following:
(1) All known errors in the first edition would be corrected; (2) more would be said about
debugging; (3) more problems would be given, including problems that would help stu-
dents confront very basic issues in the rudiments of MATLAB; (4) solutions to selected
problems would appear with downloadable code on the bookÊs new website (www.rout
ledge.com/9780415535946) rather than in the back of the book to allow for more extensive
code, updating of the programs if necessary, and addition of new programs as needs and
curiosities arose; (5) there would be a tutorial on designing Graphical User Interfaces, or
GUIs, which enable a user to interact with a program using graphics to run experiments
within MATLAB; (6) there would be a tutorial in designing experiments using Psychtool-
box, a freely available MATLAB toolbox that is specifically geared to behavioral science
Preface xi
research; and (7) special tricks and new functions, developed or discovered since 2007,
would be featured, including several developed by the authors to solve sometimes thorny
problems that arise in data collection and data presentation.
In preparing the second edition, Jon and David made these changes while retaining the
main organization of the bookÊs first edition. As before, readers are ushered to the mate-
rial slowly and in as a welcoming a way as possible, with more specialized topics coming
as the chapters continue. Also as in the first edition, there is continued use of a style that
worked well before·introducing a new problem or challenge, presenting associated code,
and then presenting the output. In addition, as in the first edition, each chapter starts with a
list of things to be done followed by commands that get them done. These start-of-chapter
lists let you use the book as a reference once you understand the basics of MATLAB. Thus,
after you have worked your way through the book, you will be able to turn to a section and
quickly get the detailed information you need to complete the programming task you are
undertaking. All the commands are listed as well in a single Command Index near the back
of the book, another innovation of the second edition relative to the first.
Another way we have made the text as user-friendly as possible is to update the website for
this book. On this site, you will be able to find and copy the programs and program outputs
in this volume. The outputs on the website have color, motion, and sound, whereas those
modalities are absent from the printed edition.
As shown in the list of new features, the second edition has a chapter on Psychtoolbox. This
is a free, popular, MATLAB-based toolbox for running behavioral experiments. Neither
Jon nor David had used Psychtoolbox before, simply because it wasnÊt essential for their
work. It happened, however, that Brad Wyble, a newly hired faculty member in the Penn
State Psychology Department (the department where David works), had extensive experi-
ence with Psychtoolbox. Jon and David invited Brad to prepare a chapter for the book on
Psychtoolbox, and, to their great satisfaction, he agreed.
BradÊs area of expertise is vision, the domain of behavioral science in which, it happens,
Psychtoolbox is used the most. With his extensive background in computer science·Brad
was a computer science major as an undergrad and did research in computer science labs
after completing his PhD at Harvard·he proved to be a wonderful addition to the team.
His involvement in the book was limited to the one chapter he prepared, plus his review
of this Preface, as per the agreement he made with Jon and David. Any errors in the book,
then, outside of the Psychtoolbox chapter and the Preface are not due to Brad. By the same
token, any errors in the Psychtoolbox chapter and in the Preface are as much JonÊs and
DavidÊs fault as they are, or might be, BradÊs. In general, any mistakes rest squarely with
Jon and David, or most especially David, who, after having had several years to mull over
the transition from the first edition to the second, should have gotten things right by now!
The last thing we want to say in this preface echoes what we say in the main text about
responsiveness to feedback. It is fine to be open to feedback from a computer, as we urge
you to be, but it is also good to be open to feedback from people. If you spot something that
you think could be better, please let us know. If you have suggestions for things to include
in a future edition, give us those suggestions. If you want help with your programming, we
cannot serve as consultants to you. We appreciate understanding on that last point. To get in
touch with us, you can use one or more of our e-mail addresses: [email protected], jaughan@
hamilton.edu, or [email protected]. We hope you will find this book useful.
Acknowledgements
There are others who deserve praise and thanks for their contributions, direct and indirect.
First, we express our appreciation to the students who took the MATLAB courses offered
by David at Penn State and by Jon at Hamilton, and who also were exposed to MATLAB
by Brad. Teaching these students helped us see which programming concepts are transpar-
ent and which are less so.
Several students in our classes and in our labs played especially important roles in helping
us hone our MATLAB instruction. We thank Penn State students Max Bay, Katie Chap-
man, Chase Coelho, Rajal Cohen, Samantha Debes, Jeff Eder, Jason Gullifer, Lanyun
Gong, Derek Henig, Joe Santamaria, Garrett Swan, Matt Walsh, and Robrecht van der Wel.
We thank Hamilton College students Deborah Barany, Julia Brandt, Hallie Brown, Drew
Linsley, Ramya Ramnath, and Anthony Sali. Others who provided valuable feedback are
Debra Boutin, Gillian Dale, Mike Frederick, Michael Romano, and Doug Weldon. Mario
Kleiner provided helpful information about Psychtoolbox.
We also wish to thank the reviewers who provided feedback on the revision plan: Simon
Farrell, University of Bristol, UK; Alen Hajnal, University of Southern Mississippi, USA;
and an anonymous reviewer.
This book was completed while the first author was on sabbatical in Los Angeles, at UCLA
and USC, where he was supported in part by a fellowship from the John Simon Guggenheim
Memorial Foundation. Brad WybleÊs research was supported at the time of this writing by
NSF grant BCS #1331073. JonÊs research has been supported by grants from the National
Science Foundation and the National Institutes of Health, as has DavidÊs. We all appreciate
this support, not to mention the support of the institutions that have paid our salaries.
We also wish to express our thanks to Paul Dukes at Psychology Press/Taylor & Francis,
who was instrumental in opening the door for the second edition of the book. Paul called
on his colleague, Debra Riegert, to work with us to bring the work to completion. Debra
was responsive and helpful at every stage. We appreciate her help as well as the further
assistance of Angela Halliday at Routledge/Taylor & Francis, who helped with the bookÊs
and websiteÊs production.
xii
About the Authors
David A. Rosenbaum is a cognitive psychologist whose main interests are human per-
ception and performance. His main research contribution has been joining cognitive psy-
chology and motor control. Rosenbaum attended public schools in Philadelphia and then
attended Swarthmore College (B.A., 1970 1973) and Stanford University (Ph.D., 1973
1977). He worked at Bell Laboratories (1977 1981), Hampshire College (1981 1987),
and the University of Massachusetts, Amherst (1987 1994). He has been at Pennsylvania
State University since 1994, where he was named Distinguished Professor of Psychology
in 2000. Rosenbaum was a recipient of a National Science Foundation Graduate Fellow-
ship (1973 1976), a National Institutes of Health Research Career Development Award
(1985 1990), and a National Institutes of Health Research Scientist Development Award
(1992 1997). His work been supported by grants from the National Science Foundation
(NSF) and the National Institutes of Health, as well as grants from the Dutch, French, and
German equivalents of NSF. Rosenbaum is a Fellow of the American Association for the
Advancement of Science, the American Psychological Association, the American Psycho-
logical Society, and the Society of Experimental Psychologists. He served as Editor of
Journal of Experimental Psychology: Human Perception and Performance (a publication
of the American Psychological Association) from 2000 to 2005. He was awarded a Gug-
genheim Foundation Fellowship in 2012 for the 2013 2014 academic year. Besides being
the author of the first edition of this book, David is the author of a textbook on motor
control [Rosenbaum, 2010] and the author of a book applying DarwinÊs theory of natural
selection to cognitive psychology [Rosenbaum, 2013].
xiii
xiv About the Authors
Brad Wyble studies attention, perception, and memory. He attended public schools in Lan-
caster, Pennsylvania, after which he obtained a B.A. in computer science from Brandeis
University (1991 1995) and a Ph.D. in psychology from Harvard University (1996 2003).
He was a postdoctoral fellow at the University of Kent in Canterbury, England (2003
2007), University College, London (2007), and MIT (2007 2009). He was subsequently an
assistant professor at Syracuse University (2009 2012) and is now an assistant professor at
Pennsylvania State University in the Department of Psychology. Wyble was a recipient of a
National Science Foundation Graduate Fellowship (1997 2000), he was a Sackler Fellow
(2001 2002), and he has been supported by grants from the National Science Foundation,
the Office of Naval Research, and the National Institutes of Health. He serves as a consult-
ing editor for the Journal of Experimental Psychology: Human Perception and Perfor-
mance, and as an associate editor for the journal Frontiers in Cognition.
1. Introduction
Computers are vital in every branch of science today, and behavioral science is no excep-
tion. When behavioral scientists use computers to obtain responses in questionnaires, pres-
ent visual stimuli, display brain images, generate data graphs, or write manuscripts, their
ability to make efficient progress in their research depends largely on their ability to use
computers effectively.
Many specialized computer packages let behavioral scientists do their work, and each one
takes some time to learn. It is useful to know how to use these specialized packages, but it is
also tantalizing to consider the possibility of learning how to program for yourself. The reason
is that all specialized computer packages rely on underlying code, and knowing how to gener-
ate such code yourself can allow you to be self-sufficient or nearly so in your own research.
Suppose, for example, that you want to develop a mathematical model of some cognitive
process. It is convenient to be able to write a program that lets you explore the mathemati-
cal model freely, seeing the results obtained with different equations, different parameter
values, and so on. Similarly, to analyze data in ways that would be cumbersome with exist-
ing spreadsheet applications, it is refreshing to be able to write the analysis program to
your own specifications. For example, to view graphs of obtained or theoretical data in a
variety of forms, it is useful to be able to generate the graphs quickly and easily, however
you please, not just as stipulated by an existing graphics package.
The computer language introduced here, MATLAB, provides you with these capabilities.
MATLAB is available from The MathWorks (www.mathworks.com), a company with which