12 Introduction unwanted events and building safeguards into your programs so you're not confronted with bogus results later on. The final sense in which it is important to be open to negative results is that you should not be complacent when your program runs and gives you results,especially beautiful ones, that cause you to blush with quixotic pride.Here is an example. The numbers I through 8 are assigned to a matrix calledx.These numbers are sessior which comprise the independent vanable of a nctonal benavoral science study. edependent variable is y,a se of fie ona scores guotestoploiIhedi nds with a sp with plot comm e for th ampe)tel MATLAB ng the ho tical axis Th than te AR axis using the nd The r the mand.(More details about these com over them here.) Code1.8.1: 8368600210.570.360.60.321 plot (,'ko-) ×1im(091) label('Session') ylabel('score on Test') When you look at the output,you are impressed by the beauty of the results. Output 1.8.1:
12 Introduction unwanted events and building safeguards into your programs so youÊre not confronted with bogus results later on. The final sense in which it is important to be open to negative results is that you should not be complacent when your program runs and gives you results, especially beautiful ones, that cause you to blush with quixotic pride. Here is an example. The numbers 1 through 8 are assigned to a matrix called x . These numbers are session numbers, which comprise the independent variable of a fictional behavioral science study. The dependent variable is y , a set of fictional scores. After x and y have been defined, a command is used to plot the data. This command ends with a special instruction, in quotes, to plot the data in black ( k ), using circles ( o ), with connecting lines ( − ). Within the plot command, you accidentally (or on purpose for this example) tell MATLAB to plot x along the horizontal axis and to plot x along the vertical axis, rather than telling MATLAB to plot x along the horizontal axis and y along the vertical axis. Three more lines of code follow. One sets the limits of the x axis to ensure that the first point is plotted (a need that arises for this particular graph). The second specifies the label for the x axis, using the xlabel command. The third specifies the label for the y axis, using the ylabel command. (More details about these commands will be given in Chapter 9. You can just skim over them here.) Code 1.8.1: x = [1 2 3 4 5 6 7 8]; y = [0.39 0.47 0.60 0.21 0.57 0.36 0.64 0.32]; plot(x,x,'ko−') xlim([0 9]) xlabel('Session') ylabel('Score on Test') When you look at the output, you are impressed by the beauty of the results. Output 1.8.1: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 Session Score on Test
Introduction 13 made One and in a comment ins error wa accordingly).the quite different. Code 1.8.2: 0.60 &Correction made here! eon Test') Output 1.8.2: The now you F elcom constructive comments 1.9 Programming With a Friend No matter how open you may be to negative feedback.it is hard to catch all the mistakes you may make.And no matter how useful it may be to talk aloud in forming your plan for a aenoioh.cyfadnomiorahkcpoakhneoaomenpmiaiheypeoay
Introduction 13 Before calling a press conference, however, it would be advisable for you to check your work. In this case, the results look too good to be true, and in fact, they are. An error was made. Once the error has been found and fixed (with a comment inserted in the program accordingly), the results look quite different. Code 1.8.2: x = [1 2 3 4 5 6 7 8]; y = [0.39 0.47 0.60 0.21 0.57 0.36 0.64 0.32]; plot(x,y,'ko-') % Correction made here! xlim([0 9]) xlabel('Session') ylabel('Score on Test') Output 1.8.2: The point of this example is that you should avoid being too self-congratulatory, at least until you know you have something to be very proud of. We hope you will reach that point! Be open to negative feedback. In that connection, we authors welcome corrections and suggestions about ways to improve this book. Feel free to contact us. We will welcome constructive comments. 1.9 Programming With a Friend No matter how open you may be to negative feedback, it is hard to catch all the mistakes you may make. And no matter how useful it may be to talk aloud in forming your plan for a computer program, you may feel uncomfortable speaking to no one in particular, especially when others are in earshot. A good way to avoid these problems is to have a friend by your side while you program. This is one of the best ways to program, in our opinion. Apart from the fact that the interactions can be fun, having two pairs of eyes and ears on a problem can spur creativity
14 Introduction We encourage you to program with someone else.The co-authors of this text often share questions and suggest solutions with each other,even though we usually collaborate at a distance.If you are using this book in a course,we encourage your instructor to find ways of grading your work so cooperation with others counts for you,not against you. 1.10 Writing Concise Programs It is fairly easy to write a program that has many unnecessary variables and superfluous lines It is harder.at least early in training.to write a program that does the same job with few variables and lines.It becomes a source of pride to programmers when they write concise programs.Such programs do more than appeal to programmers'aesthetic sense.Concise pro grams also tend to finish in less time than programs that are verb ose,go on and on,are redur dant,and have far too many words in them,as in this needlessly long sentence that have ended long ago had we not wanted to make the point that excess verbiage isn't helpful Sometimes,but not second m or even ys. pend. the prog ust solve a problem on whi on can lit y fi all potential dat aid.it is of c rite nd n set ita ide for a while.Our ce the but only to the ey Don'bout cd tht'srefkehader foryouor others to understand it. 1.11 Writing Clear Programs ciple in the list above),you should write programs that are as easy as possible to read and understand program elarity hecomes especially important when you have written many programs.If you return to a program that you wrote days or weeks ago and find yourself unable to understand it,you will be very frustrated. There are several things you can do to make your programs clear.One is to use extra lines of code or extra variables to make the structure of the program transparent.For example,if you need to divide one term by another and the numerator and denominator both contain complex expressions,it usually helps to have one variable for the terms in the numerator and another variable for the terms in the denominator.The quotient can then be expressed as the ratio of the two variables.The program might have a few more variables than are strictly required,but it will be easier for you and others to understand the code later Fo e program p OL rathe r than call the de d have helpe than y. ing those me fu mes ght have pre plotting of x against x rath y against
14 Introduction We encourage you to program with someone else. The co-authors of this text often share questions and suggest solutions with each other, even though we usually collaborate at a distance. If you are using this book in a course, we encourage your instructor to find ways of grading your work so cooperation with others counts for you, not against you. 1.10 Writing Concise Programs It is fairly easy to write a program that has many unnecessary variables and superfluous lines. It is harder, at least early in training, to write a program that does the same job with few variables and lines. It becomes a source of pride to programmers when they write concise programs. Such programs do more than appeal to programmersÊ aesthetic sense. Concise programs also tend to finish in less time than programs that are verbose, go on and on, are redundant, and have far too many words in them, as in this needlessly long sentence that should have ended long ago had we not wanted to make the point that excess verbiage isnÊt helpful. Sometimes, but not always, a concise program can reduce the time to run a program by seconds, minutes, hours, or even days. If the program must solve a problem on which peopleÊs lives depend, finding a quick solution can literally mean the difference between life and death. In more mundane terms, when a program is used to acquire behavioral data, if it runs too slowly, not all potential data can be captured. That said, it is of course possible to write too concisely, so the code is obscure to other readers and maybe even to yourself once youÊve set it aside for a while. Our advice, then, is to be concise, but only to the extent necessary. DonÊt obsess about writing code thatÊs ultra-brief if it makes it harder for you or others to understand it. 1.11 Writing Clear Programs As just said, program conciseness can enhance clarity, but thatÊs not always the case. Just as you should be as lucid as possible about what your program must do (the second principle in the list above), you should write programs that are as easy as possible to read and understand. Program clarity becomes especially important when you have written many programs. If you return to a program that you wrote days or weeks ago and find yourself unable to understand it, you will be very frustrated. There are several things you can do to make your programs clear. One is to use extra lines of code or extra variables to make the structure of the program transparent. For example, if you need to divide one term by another and the numerator and denominator both contain complex expressions, it usually helps to have one variable for the terms in the numerator and another variable for the terms in the denominator. The quotient can then be expressed as the ratio of the two variables. The program might have a few more variables than are strictly required, but it will be easier for you and others to understand the code later. A second practice to make your code clear is to give your variables meaningful names. For example, in the program presented earlier (Codes 1.8.1 and 1.8.2), it would have helped to call the independent variable session rather than x and to call the dependent variable test_score rather than y . Using those meaningful variable names might have prevented the „accidental‰ plotting of x against x rather than the more appropriate plotting of y against x
Introduction 15 or the om ments are pre a perce Programmers comment in different ways.Some interleave con ments and executable lines of code Others tend to provide comments above the executable code (at the start of the am) putting relatively fe ments in the body of the The first autho this book p efers the latter method because it allows him to vide a conceptual plan for the program to follow.along with introductions of the variables he will be using.He prefers not to have too many comments interspersed with code within his programs because he finds them distracting to read and,frankly,a pain to write. Providing comments at the start of a program can help you start your programming session by combining the need for commenting with the need for"speaking aloud."Developing a plan for a program is often aided by putting the plan into words,as stated earlier(Section 1.5).Being able to say what your program should do will help you write the code you need.The first author often sits down and starts typing the description of what his program will do,editing the emerging comment until he reaches the point where he thinks the procedure he's descrbing is as clear and mechanically doable as he can make it.Then he begins coding.testing one part of the code at a time.saving successive edits in files with higher and higher version numbers. executa ble statements)are typica LAB s are usu once yo u gain fa L e exe h ment comma ed below will be explain d in more de Code1.11.1: &Largest_So_Far_01 the largest value in the one-row matrix v. tso_fa minus in set n9 to 1 incre of v equal If the 91 arge so_far. through the w hole out 1 argest s0far. ray,print V=1733392681815401 largest so far -inf: for i=1:1ength(V) if v(i)>largest_so_far largest so far v(i) end end largest_so_far
Introduction 15 A third practice to improve program clarity is to add comments. Comments are nonexecutable statements that provide information for the programmer (or reader) instead of for the computer. In MATLAB, comments are preceded by a percent sign ( % ), as shown in Code 1.8.2. Programmers comment in different ways. Some interleave comments and executable lines of code. Others tend to provide comments above the executable code (at the start of the program), putting relatively few comments in the body of the program. The first author of this book prefers the latter method because it allows him to provide a conceptual plan for the program to follow, along with introductions of the variables he will be using. He prefers not to have too many comments interspersed with code within his programs because he finds them distracting to read and, frankly, a pain to write. Providing comments at the start of a program can help you start your programming session by combining the need for commenting with the need for „speaking aloud.‰ Developing a plan for a program is often aided by putting the plan into words, as stated earlier (Section 1.5). Being able to say what your program should do will help you write the code you need. The first author often sits down and starts typing the description of what his program will do, editing the emerging comment until he reaches the point where he thinks the procedure heÊs describing is as clear and mechanically doable as he can make it. Then he begins coding, testing one part of the code at a time, saving successive edits in files with higher and higher version numbers. Here is an example of one such program. The comments in the opening section (before any executable statements) are typical of what the first author writes. In a short program like this, no further comments are usually needed, because once you gain familiarity with MATLAB, the meanings of the executable statements can usually be understood if the context is clear. All the commands used below will be explained in more detail later in this book. Code 1.11.1: % Largest_So_Far_01 % Find the largest value in the one-row matrix V. % Initialize largest_so_far to minus infi nity. % Then go through the matrix by fi rst setting i to 1 % and then letting i increase to the value equal % to the number of elements of V, given by length(V). % If the i-th value of V is greater than largest_so_far, % reassign largest_so_far as the i-th value of V. % After going through the whole array, print out % largest_so_far. V = [7 33 39 26 8 18 15 4 0]; largest_so_far = -inf; for i = 1:length(V) if V(i) > largest_so_far largest_so_far = V(i); end end largest_so_far
16 Introduction Output 1.11.1: largest so far 39 The foregoing program can be adapted to find the largest value of other arrays,including much larger ones.We include the program here to give you a taste for what MATLAB pro grams look like.We also want to convey the idea that it's advisable to test programs on small scales.In general,it's advisable to work on'toy"problems before scaling up to larger ones. This program was tested with an array of length 9.Nine numbers is a more tractable length to use at first than 9.000.000.Just to be sure there are no problems.the program should also be tested with sample data sets in which the largest value is in the first or last position of the matrix because many program errors only reveal themselves at such boundanes One last point about program clarity follows.Like all w riting.a progra m is sed for severa udiences Apart three audiences to keep in min First,there is the computer.The computer,the machine.must be able to deal with the gram i The second audience is a colleagu who may wish to evaluate or adap nd with problem vond the con ents you provided. The third audience is your future self who.another day.may look back at the prior work At that later time,you may be faced with understanding what you did without a detailed memory of how you addressed the problem.In the urgency of writing your program to solve an immediate problem you may take shortcuts such as using yery brief mnemonics for variable names,the meaning of which may be forgotten in the future.To ensure against this unhappy outcome.you may find that once the program is completed,it will serve you to spend a little time clarifying the variable names and adding a few judicious comments. Once you have made these changes.be sure to test the program again,lest your clarification inadvertently produced a new error. In that spirit,here is the program from Code 1.11.1,with the variable name V replaced by theDataarray.A couple of other variables and comments have been added as well.Is it clearer to read?Is the result different?Try to make your own programs"self-documenting' by selecting variable names and comments that are as self-explanatory as possible Code1.11.2: 号Largest So Far02 Find the largest value in the one-row matrix theDataArray. 8 Initialize largest_so_far to minus the matrix,by irst setting to1 intinity. and then letting i increase to the value equal
16 Introduction Output 1.11.1: largest_so_far = 39 The foregoing program can be adapted to find the largest value of other arrays, including much larger ones. We include the program here to give you a taste for what MATLAB programs look like. We also want to convey the idea that itÊs advisable to test programs on small scales. In general, itÊs advisable to work on „toy‰ problems before scaling up to larger ones. This program was tested with an array of length 9. Nine numbers is a more tractable length to use at first than 9,000,000. Just to be sure there are no problems, the program should also be tested with sample data sets in which the largest value is in the first or last position of the matrix because many program errors only reveal themselves at such boundaries. One last point about program clarity follows. Like all writing, a program is composed for several audiences. Apart from yourself (the person writing and using the code), there are three audiences to keep in mind. First, there is the computer. The computer, the machine, must be able to deal with the program in the way you wish. At the very least, the program supplied to the computer must be syntactically and logically correct. The second audience is a colleague, who may wish to evaluate or adapt your program for a related purpose. The colleague may need to understand your program and its logic, with or without your direct advice, and without any particular insights into how you addressed the problem beyond the comments you provided. The third audience is your future self who, another day, may look back at the prior work. At that later time, you may be faced with understanding what you did without a detailed memory of how you addressed the problem. In the urgency of writing your program to solve an immediate problem, you may take shortcuts, such as using very brief mnemonics for variable names, the meaning of which may be forgotten in the future. To ensure against this unhappy outcome, you may find that once the program is completed, it will serve you to spend a little time clarifying the variable names and adding a few judicious comments. Once you have made these changes, be sure to test the program again, lest your clarification inadvertently produced a new error. In that spirit, here is the program from Code 1.11.1, with the variable name V replaced by theDataArray . A couple of other variables and comments have been added as well. Is it clearer to read? Is the result different? Try to make your own programs „self-documenting‰ by selecting variable names and comments that are as self-explanatory as possible. Code 1.11.2: % Largest_So_Far_02 % Find the largest value in the one-row matrix theDataArray. % Initialize largest_so_far to minus infi nity. % Then go through the matrix, by fi rst setting i to 1 % and then letting i increase to the value equal