Introduction 7 ·Work incrementally .Be open to negative feedback .Program with a friend. Write concise programs .Write clear programs. .Write correct programs Consider each of these principles in turn. 1.5 Deciding If a Program Is Needed and Whether You Should Write It The first principle is less obvious than you might suppose.Consider the problem discussed above(finding the largest of a set of values).The numbers corresponding to the bars in Figure 1.3.2 are as follows: 73339268181540 Do you need a computer program to find the largest of these values?Obviously not.You know that the largest of these numbers is 39 and that this largest number occupies the third slot in the serie If you only had to find the lagest value in this rray. be fooli h to write a program for this tas pt as an exerci On the oth hand,if you were quite sure you d often need to find the largest number in each of a large numb 金 es,w sen e.A progran uld be too taxing to perform by nt If .also m for a task if somec Our answer to this question is analogous to the answer a math teacher might give to a e this theorem if it's been oved before?"Prac tice makes perfect"the teacher m ply.He or she may go on:"Even if true perfection is beyond your reach,practice will increase the chance of your proving something new yourself. Our view of programming is the same.You might be able to locate programs that already do things you need to,and it may make sense for you to use those programs,especially for problems that seem very complicated or that are beyond your technical ability.But the more practice you get programming.the more likely it will be that you will be able to gen- erate programs that either solve new problems or solve old problems in new ways.Don't be discouraged if it takes an hour or more to get your first"real"program up and running.even if you might have done the same computation by hand in a minute or less.As you develop
Introduction 7 Ć Work incrementally. Ć Be open to negative feedback. Ć Program with a friend. Ć Write concise programs. Ć Write clear programs. Ć Write correct programs. Consider each of these principles in turn. 1.5 Deciding If a Program Is Needed and Whether You Should Write It The first principle is less obvious than you might suppose. Consider the problem discussed above (finding the largest of a set of values). The numbers corresponding to the bars in Figure 1.3.2 are as follows: 7 33 39 26 8 18 15 4 0 Do you need a computer program to find the largest of these values? Obviously not. You know that the largest of these numbers is 39 and that this largest number occupies the third slot in the series. If you only had to find the largest value in this particular array, you would be foolish to write a program for this task, except as an exercise. On the other hand, if you were quite sure you would often need to find the largest number in each of a large number of arrays of unpredictable sizes, writing a program would make more sense. A program is useful, then, for performing a well-defined task that would be too taxing to perform by hand. The second part of the first principle, whether you should write the program yourself, also deserves comment. If you decide you need a program, it may or may not make sense for you to write the program yourself. Why should you write a program for a task if someone else has done so before? Our answer to this question is analogous to the answer a math teacher might give to a rebellious student: „Why should I prove this theorem if itÊs been proved before?‰ „Practice makes perfect,‰ the teacher may reply. He or she may go on: „Even if true perfection is beyond your reach, practice will increase the chance of your proving something new yourself.‰ Our view of programming is the same. You might be able to locate programs that already do things you need to, and it may make sense for you to use those programs, especially for problems that seem very complicated or that are beyond your technical ability. But the more practice you get programming, the more likely it will be that you will be able to generate programs that either solve new problems or solve old problems in new ways. DonÊt be discouraged if it takes an hour or more to get your first „real‰ program up and running, even if you might have done the same computation by hand in a minute or less. As you develop
8 Introduction programming expertise.you will become more efficient and productive,and you'll be able to apply your new skills to other problems. 1.6 Being as Clear as Possible About What Your Program Should Do If you decide that you need a r ram and that you should write it yourself,you will need to he as clea ssible abou should do This is r said than done Thinking through the workings of a p ects of program- ming.even harder in some cases than getting the syntax right. Return to the problem of finding the largest value in an array.It turns out that MATLAB provides a program (or more precisely,a fiunction).called max,that lets you find the maximum of a set of values (see Chapter 4).You can use this function to get the larg- est value in a matrix without having to reinvent the function yourself.Nevertheless,it is worth thinking through the way you would identify the largest value in an array.Work- ing through this example-however simple it may seem-will help you begin to"think programmatically. To think through what a program must do to find the largest value in an array of numbers imagine that you have a row of numbers like the one above,but you can only see one of the numbers at a time say,by sliding the hole in a card across the row.Under this circum- stance,you can determi e the larges valu value so far.I you wer actually d first place in the card over th Irst nu which is that 7 e you to revea rger than now you d te that 33 umb seen,and you' for the rest w time y value larger than la est value so far.afte list,Largest_Far will be the largest of all the values. Here is a flow chart for the procedure,along with some other items you'd need to get the job done.One of these other items is telling the program how many values there are in the list.We give the list the name V.There aren=9 values in V. Another thing that needs to be done is initializing Largest value so Far to an extremely small value,namely,minus infinity (which can be expressed in MATLAB as -inf).We do this because whenever a new number is tested,it must be compared to some prior value.Starting with-inf ensures that the first value will be called the largest pro- vided it is larger than-inf.It may stay that way if no larger value comes along. The third thing that needs to be done is providing an index,i.for each successively encountered value in V.An index for a value is the position of the value in the matrix For the first item,i-1,for the second item,i=2,and so forth.Initially,i is set to 0.Each time a new number is compared to Largest value so Far,the variable d by 1,until i is greater thar i-th va V enoted 1 is assigned to Largest value so Far if v(i)is larger than the current value o
8 Introduction programming expertise, you will become more efficient and productive, and youÊll be able to apply your new skills to other problems. 1.6 Being as Clear as Possible About What Your Program Should Do If you decide that you need a program and that you should write it yourself, you will need to be as clear as possible about what your program should do. This is easier said than done. Thinking through the workings of a program can be one of the hardest aspects of programming, even harder in some cases than getting the syntax right. Return to the problem of finding the largest value in an array. It turns out that MATLAB provides a program (or more precisely, a function ), called max , that lets you find the maximum of a set of values (see Chapter 4). You can use this function to get the largest value in a matrix without having to reinvent the function yourself. Nevertheless, it is worth thinking through the way you would identify the largest value in an array. Working through this example·however simple it may seem·will help you begin to „think programmatically.‰ To think through what a program must do to find the largest value in an array of numbers, imagine that you have a row of numbers like the one above, but you can only see one of the numbers at a time·say, by sliding the hole in a card across the row. Under this circumstance, you can determine the largest value by finding the largest value so far . If you were actually doing this, youÊd first place the hole in the card over the first number, which is 7. Then, youÊd remember that 7 is the largest value youÊve seen, and move the card to reveal the 33. Thirty-three is larger than 7, so now youÊd note that 33 is the largest number youÊve seen, and youÊd move the card again. After seeing 39, you would revise the largest number seen to that value. Continuing and not encountering any number larger than 39 for the rest of the series, that would be the number youÊd report. Now translate this algorithm into a program. Assign some very small value to a variable called, for instance, Largest_Value_So_Far . Then, proceeding from left to right, every time you encounter a value larger than Largest_Value_So_Far, reassign that new value to Largest_Value_So_Far . After you have evaluated the last item on the list, Largest_Value_So_Far will be the largest of all the values. Here is a flow chart for the procedure, along with some other items youÊd need to get the job done. One of these other items is telling the program how many values there are in the list. We give the list the name V . There are n = 9 values in V . Another thing that needs to be done is initializing Largest_Value_So_Far to an extremely small value, namely, minus infinity (which can be expressed in MATLAB as –inf ). We do this because whenever a new number is tested, it must be compared to some prior value. Starting with –inf ensures that the first value will be called the largest provided it is larger than –inf . It may stay that way if no larger value comes along. The third thing that needs to be done is providing an index, i , for each successively encountered value in V . An index for a value is the position of the value in the matrix. For the first item, i = 1 , for the second item, i = 2 , and so forth. Initially, i is set to 0 . Each time a new number is compared to Largest_Value_So_Far, the variable i is incremented by 1, until i is greater than n . The i -th value of V , denoted V(i) , is assigned to Largest_Value_So_Far if V(i) is larger than the current value of
Introduction9 .program stops and the value n=9 Largest_Value_So_Far=-inf i=0 i=i+1 Yes No NoV()Largest Value_So_Far? Yes Largest_Value_So_Far=V() Print Largest_Value_So_Far Figure1.6.1 A flowchart like this can serve as the conceptual foundation for the code needed to get a computer to find the largest value in an array.You don't have to draw a flowchart before you write MATLAB code,however.Some people only imagine flowcharts or the steps corresponding to them.Drawing flowcharts in your head obviously gets easier as you get more practice with programming.Early in practice,however,it is advisable to sketch the steps your programs will follow. How do you come up with a flowchart or its corresponding steps in the first place?The honest answer is that no one knows.Anyone who could give the answer would,in effect know how thoughts originate,and no one at this time has a clue about that.If you solve this problem,a Nobel Prize awaits you. You can,however,consider some practical advice about how to come up with the proce dures One suggestion is to t out Iou Imagine yourse n,step by s ,m ry car to mak e expl th Ir. P oK next I'll t he erion I can't quite ready to write all the ode ou need.Ultimately u'll need to be about the instructionsy ms contain.Relvins omiracle just w on't work and toe cis that computers for al their speed.are ignorant and infle ible.They do exactly and only what they're told to do
Introduction 9 Largest_Value_So_Far. When i is larger than n , the program stops and the value of Largest_Value_So_Far is printed out. Figure 1.6.1 A flowchart like this can serve as the conceptual foundation for the code needed to get a computer to find the largest value in an array. You donÊt have to draw a flowchart before you write MATLAB code, however. Some people only imagine flowcharts or the steps corresponding to them. Drawing flowcharts in your head obviously gets easier as you get more practice with programming. Early in practice, however, it is advisable to sketch the steps your programs will follow. How do you come up with a flowchart or its corresponding steps in the first place? The honest answer is that no one knows. Anyone who could give the answer would, in effect, know how thoughts originate, and no one at this time has a clue about that. If you solve this problem, a Nobel Prize awaits you. You can, however, consider some practical advice about how to come up with the procedures for computer programs. One suggestion is to talk out loud as you imagine yourself doing the task you wish to program, step by step, much as we did with the imaginary card above. Talking out loud may enable you to make explicit whatever implicit knowledge you bring to bear as you do the task, as if you were explaining the task to a friend. Hearing your own words will also help you identify those things youÊre not clear about. If you hear yourself say, „OK, next IÊll somehow figure out which of the values might be OK based on some criterion I canÊt quite articulate but I have a vague feeling about,‰ then youÊre not quite ready to write all the code you need. Ultimately, youÊll need to be completely explicit about the instructions your programs contain. Relying on a miracle just wonÊt work, and the reason, just to be explicit, is that computers, for all their speed, are ignorant and inflexible. They do exactly and only what theyÊre told to do
10 Introduction This is one way in which programming is very different from other forms of communica- tion.When you speak to other people,you assume-usually correctly-that they have some knowledge that lets them fill in missing information.Not so with computers,or at least conventional computers given stand-alone programs.Writing successful computer programs requires a degree of explicitness that is unparalleled in other aspects of human experience.This is one reason why learning to write computer programs can be challeng- ing.On the other hand,being explicit to the point that a computer can carry out instructions may sometimes carry over well to other things you do.like writing papers or reaching agreements with others about who will do what in connection with some project 1.7 Working Incrementally Another challenge of progr coauidy makin ally.By we mea m yo little at a time builds you al.: build you re you go ent is added.by e the ba nent is solid befor the first floo is added.and so on.During p n develo ent.you will often find it useful to ger rate intermediate output to ver rify that each sten works as expe cted.You may later inhibit that output when the program is completed and is no longer needed.Think of this incremental D ess as the digital equivalent of the ancient woodworking adage (attributed to John Florio,1591).Alwaies measure manie,before you cut anie("Measure twice,cut once.") When you're reasonably sure your program works and before you add another component or make other significant changes.save the program with a file name unique to the last working version.The moment you prepare to make changes to the program,save the file with a new name or version number before putting in any changes.Follow the American folk adage,"If it ain't broke,don't fix it."Too often,attempts to further develop a program will,in fact,break it,or otherwise reveal some weakness in it,and you might want to go back to an earlier version.You'll be glad you have one Remember,too,that computer storage is cheap.There is no harm in having a folder full of documents called Ma rogram_01.m,Max_Program_02 .m,Max Program 03.m u actual work s Ma? Pro othing wrong with such a high nun ay the ons I versions ATLAB es it easy to compare the ng connec sa compa ferences betweer wo vers a program,simila ck changes”inMic 0 ligh 1.8 Being Open to Negative Feedback How can you tell if your prog ram works?as you consider this question one attitude should rule over all others:Be tive fee back.if you treat ne gative feedback as a help rather than a hindrance. ou will become a better,and certainly happier,programmer than if you treat ngative fcedback in a ngativeay. The research of psychologists Carol Dweck and Janine Bempechat(1980)is relevant in this regard.Dweck and Bempechat distinguished between people who take negative feedback
10 Introduction This is one way in which programming is very different from other forms of communication. When you speak to other people, you assume·usually correctly·that they have some knowledge that lets them fill in missing information. Not so with computers, or at least conventional computers given stand-alone programs. Writing successful computer programs requires a degree of explicitness that is unparalleled in other aspects of human experience. This is one reason why learning to write computer programs can be challenging. On the other hand, being explicit to the point that a computer can carry out instructions may sometimes carry over well to other things you do, like writing papers or reaching agreements with others about who will do what in connection with some project. 1.7 Working Incrementally Another challenge of programming is translating your procedural ideas into language the computer can understand. Here it is useful to work incrementally. By this we mean you should build your program a little at a time, making sure each part works before you go on to another part that depends on what youÊve just written. You should build your program the way a reliable contractor builds a house, by making sure the foundation is solid before the basement is added, by making sure the basement is solid before the first floor is added, and so on. During program development, you will often find it useful to generate intermediate output to verify that each step works as expected. You may later inhibit that output when the program is completed and is no longer needed. Think of this incremental programming process as the digital equivalent of the ancient woodworking adage (attributed to John Florio, 1591), Alwaies measure manie, before you cut anie („Measure twice, cut once.‰). When youÊre reasonably sure your program works, and before you add another component or make other significant changes, save the program with a file name unique to the last working version. The moment you prepare to make changes to the program, save the file with a new name or version number before putting in any changes. Follow the American folk adage, „If it ainÊt broke, donÊt fix it.‰ Too often, attempts to further develop a program will , in fact, break it, or otherwise reveal some weakness in it, and you might want to go back to an earlier version. YouÊll be glad you have one! Remember, too, that computer storage is cheap. There is no harm in having a folder full of documents called Max_Program_01.m , Max_Program_02.m , Max_Program_03.m , and so on. It may be that the version youÊll use for actual work is Max_Program_101.m . There is nothing wrong with such a high number. You can tuck away the earlier versions in a sub-folder until youÊre sure youÊll never need to look back. Having sequential versions of a program in development makes it easy to compare the changes. In this connection, it is useful to note that MATLAB has a comparison tool that highlights all differences between two versions of a program, similar to „track changes‰ in Microsoft Word. 1.8 Being Open to Negative Feedback How can you tell if your program works? As you consider this question, one attitude should rule over all others: Be open to negative feedback . If you treat negative feedback as a help rather than a hindrance, you will become a better, and certainly happier, programmer than if you treat negative feedback in a negative way. The research of psychologists Carol Dweck and Janine Bempechat (1980) is relevant in this regard. Dweck and Bempechat distinguished between people who take negative feedback
Introduction 11 h hile i more if you take n then if con ad s tha ren't you an error message that says ou"for programming.MATLAB will not give ??You don't deserve oxygen! A more likely message is something prosaic like ??Subscript indices must either be real positive integers or logicals. You might get an error message like the latter one in response to code such as Reaction Time For Trial(0)=680; All you have to do here is appreciate that it makes no sense to have the zero-th element of was entere e base error withou ting yo gpd0是efeothe t youcc the0通 Reaction_Time_For_Trial(1)-680 One reason for saying these things is that it bears message ve while machi membering that the erro not fr ou to ak f advice.Over time will get fewe ing low-level asp cts of coding (e g closing parentheses in a line of code),and you will learn what the error messages mean. More about error messages and debugging(correcting your programs)will come later in the text. Over time you will also leamn to guard against disaster when you program.We encourage you to do so by writing programs that are resilient rather than brittle.If you write a pro- gram that crashes or yields crazy results when it gets input of a different sort than what you anticipated,your program won't be of much good.For example,if you write a program that is used to collect questionnaire data.and a participant types in an age of-83.that could wreak havoc with subsequent data analyses.It doesn't matter why the participant put a minus sign in front of his or her age(if he or she is actually 83).Perhaps the partici pant thought this might help you see the number more clearly.perhaps it was just a typo or perhaps th ing cute The you anticipate can go wrong w en a program s being run.A good r gua uch th ng open t nore tha not letting your hur en the 0 ding constructively to negative fe eyou mi o means ng open all
Introduction 11 as signs of their lack of talent ( entity learners) and people who treat negative feedback as cues for ways to improve their performance ( incremental learners). It is important while programming to have the attitude of an incremental learner rather than an entity learner. You will learn more if you take negative feedback constructively than if you read such feedback as a sign that you werenÊt „cut out‰ for programming. MATLAB will not give you an error message that says ??? You don't deserve oxygen! A more likely message is something prosaic like ??? Subscript indices must either be real positive integers or logicals. You might get an error message like the latter one in response to code such as Reaction_Time_For_Trial(0) = 680; All you have to do here is appreciate that it makes no sense to have the zero-th element of an array. An array can have a first element, a second element, a third element, and so on, but it canÊt have an element numbered zero. Whether the 0 was entered in the code based on a misunderstanding or simply as a typo, you can correct the error without indicting your genes. If when you typed 0, you were referring to the first trial, you can replace the 0 with a 1 and all will be fine: Reaction_Time_For_Trial(1) = 680; One reason for saying these things is that it bears remembering that the error messages you receive while programming come from a machine, not from a person who knows what you are trying to say. When you receive an error message, it will help you to take the message as a piece of advice. Over time, you will get fewer error messages concerning low-level aspects of coding (e.g., when you have an unequal number of opening and closing parentheses in a line of code), and you will learn what the error messages mean. More about error messages and debugging (correcting your programs) will come later in the text. Over time you will also learn to guard against disaster when you program. We encourage you to do so by writing programs that are resilient rather than brittle. If you write a program that crashes or yields crazy results when it gets input of a different sort than what you anticipated, your program wonÊt be of much good. For example, if you write a program that is used to collect questionnaire data, and a participant types in an age of -83, that could wreak havoc with subsequent data analyses. It doesnÊt matter why the participant put a minus sign in front of his or her age (if he or she is actually 83). Perhaps the participant thought this might help you see the number more clearly, perhaps it was just a typo, or perhaps the participant thought he or she was being cute. The point is that you must anticipate such eventualities. All sorts of things can go wrong when a program is being run. A good programmer guards against as such eventualities. In this sense, being open to negative feedback means more than not letting your feelings be hurt when the computer beeps because you left out a punctuation mark or because you mistyped the name of a function. Responding constructively to negative feedback also means being open to all sorts of