CURR TPCS IN COGNITIV NEUROSCI
CURR TPCS IN COGNITIV NEUROSCI PSY 394U
Popular in Course
verified elite notetaker
Alea Nicole Vick
verified elite notetaker
verified elite notetaker
verified elite notetaker
verified elite notetaker
verified elite notetaker
Popular in Psychlogy
This 16 page Class Notes was uploaded by Marco Wolf on Monday September 7, 2015. The Class Notes belongs to PSY 394U at University of Texas at Austin taught by Staff in Fall. Since its upload, it has received 5 views. For similar materials see /class/181809/psy-394u-university-of-texas-at-austin in Psychlogy at University of Texas at Austin.
Reviews for CURR TPCS IN COGNITIV NEUROSCI
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/07/15
Appendix A Programming Primer and Reference You may want to start with Matlab tutorial 1 httpwww mathwnrk student centertutorials39 39 J html Summagy of MATLAB learned in this chapter Assignment and variables equal sign sets a variable equal to a value semicolon output display suppression scalars vectors matrices A scalar variable holds a single value Created by assigning a value to a variable name e x 5 A vector holds more than one value along a single dimension A matrix is similar to a vector except that it has two dimensions referred to as rows and columns Vectors and matrices can be created by Concatenation x 1 l 2 3 5 8 13 for 1x8 vector or y 1 2 3 4 5 6 for 2x3 matrix Data creation functions zeros ones rand randn linspace logspace colon Implicitly x2 5 creates x with length 2 and sets the second value to 5 Elements of a vector are accessed by indexing using parentheses xl thus refers to the rst element of x y23 is the element of y in the second row and third column operators relational lt gt lt gt and N compare 2 values and return TRUE 1 or FALSE 0 logical N NOT amp AND l OR and xorvaluel value2 compare logical values for vectors ampamp and H are shottcircuit logical operations arithmetic and A perform basic arithmetic operations rem gives the integer remainder of division general functions sumx adds all elements of a matrix x columnwise meanx computes the mean of elements in x stdx computes the standard deviation of elements in x plotxy creates a plot of yfx histx histogram of vector or matrix x findcondition nd indices of matrix elements that satisfy condition help functionname or help functioniname provides help on the function lookfor topic might work if you don t know the exact function name data creation randsampledata size replace takes samples from data concatenates all of its arguments into a single vector repmata x y replicates a scalar or matrix a in xrows and ycolumns creates a series of values incremented by l or specified size linspacefr0m t0 howmany is a more exible version of the above logspacefr0m t0 howmany creates logarithmic scale randnxy creates x by y normally distributed random numbers randx creates uniform random numbers zer0sxy creates x by y matrix of zeros 0nesxy creates x by y matrix of ones control ow functions f0r repeats one or more operations a speci ed number of times if else performs one or more operations contingent on some condition while runs until some condition is met data import and export loadO reads a Matlab file or tab delimited text file containing data only llmreadO does the same for any delimiter xlsreadO reads data from an excel sheet including column names save writes a Matlab or 7ascii f11e llmwriteO writes delimited formatted data xlswriteO writes data into an excel file possibly including column names The meat and potatoes assignment and variables A variable can be thought of as a container referred to by the variable name that can hold any numeric value the equals sign assigns a value on the right to a variable on the left For example after x 5 the variable x contains the value 5 Importantly if the variable already exists it will be overwritten with the new value Seriously if x contains all the data that the Air Force uses to drop bombs and you type x 4 then too bad for the Air Force 7 x now contains the value 4 7 no recovery no exceptions all bombs go to 4 wherever that is One seeming exception to the destroys things rule 7 and a very useful one 7 is as follows Programming languages unlike English are read righttoleft by default Thus will take the existing value of X add one to it and store the result back into X The old value of X is gone forever but it was used in an intermediate step to calculate the new value of X Ithink of variables like a mailb0X I don t have to go around to various places to collect my daily mail Instead today s mail the value appears in the mailb0X Cormack the variable name So all I have to do each day is query the variable Cormack which makes checking my mail easy semicolon The semicolon is used at the end of an input line to suppress output to the console Typing X 1 causes MATLAB to print the values in X to the command window whereas X l creates X silently This is valuable when working with large sets of numbers You will see the tremendous value in using variables when we start writing longer programs especially those with loops ScalarsI vectors and matrices regular variables aka scalars Scalars are variables that hold a single value X 5 is an eXample of creating a scalar variable vectors A vector consists of multiple values all referred to by the same variable name The individual values are referred to by the variable name and an integer index For eXample after x 1 2 3 5 7 note those are square brackets see data creation below X contains the first five prime numbers Elements are accessed using regular parentheses so the 4th value is obtained by X4 etc The number inside the brackets is the index into the vector X You can also refer to ranges of values 7 so X 2 4 are the middle three values and as I mentioned above 24 can be read as 2 through 4 inclusive You can think of a vector as a row of mailboxes like we have on rural Texas roads where all the mailboxes for the houses down a particular tumoff are in a single row at the tumoff So if there is a row of 5 mailboxes at the turnoff to Guntotin Rd then we could name the entire row guntotin and guntotin3 would then refer to the middle mailbox In addition to the above use of square brackets there are some other ways to create vectors One is to use the zeros function x zeros 5 1 which creates a vector elements long 5 rows and one column and lls it with zeroes The ones function works the same except it creates a vector filled with ones matrices and arrays Matrices are the same as vectors except they have both rows and columns ie they are 2 dimensional instead of 1 dimensional MATLAB Matrix laboratory can perform various matrix operations fast and easy so you want to use them a lot Scalar and vectors in MATLAB can be thought of as a special case ofa matrix scalars are matrices of size lxl vectors are matrices that have size of one dimension equal to one You can type in small arrays using square brackets as above inserting a semicolon each time you want to start a new row y 1 2 3 5 7 11 The variable y is now a matrix with 2 rows and 3 columns y 1 2 3 5 7 11 Individual values in a matrix are set or obtained just as with vectors except both a row index and a column index are needed Thus y2 3 2718282 Sets the element at the second row and third column to e roughly and myie y 2 3 grabs this value and places it in the variable myie You can think of matrix as being like the faculty or student mailboxes in a departmental mailroom If the name faculty referred to the faculty mailboxes then faculty4 5 would be my mailbox since it is fourth from the top and fifth from the left You can extract chunks of data from a matrix using the colon which remember can be read as through So y l 2 2 3 will give you the lower left four elements of y Used by itself the colon translates to all rows or all columns For example Y 1 I 3 returns the entire third column of y If you are familiar with a spreadsheet program such as Microsoft Excel then an analogy might be useful A scalar variable is exactly like a cell in Excel a vector is like a column or row and a matrix is like a single worksheet In fact because of correspondence it is easy to read data into MATLAB from an excel spreadsheet and vice versa This is covered below in input and output It is generally easier to create matrices with MATLAB commands designed for this pupose x zeros 5 3 creates a matrix x with 5 rows and 3 columns filled with zeros Note that this is the same thing we did to create a vector above we simply changed the second number to tell MATLAB to create three columns rather than one Note also that the new x has replaced or overwritten the one created above In addition to zeros the commands ones rand and randn are available The latter two create a matrices containing either uniform or Gaussian random numbers myrand 10 3 randn OOO 1 creates a variable myrand containing 1000 random numbers with mean 10 and standard deviation 3 Note that MATLAB automatically applies the multiplication and addition to every member of the matrix created by randn which is handy Matrices have 2 dimensions by definition and are a special case of arrays which can have any number of dimensions If you are new to programming and you try to work with arrays with more than 3 dimensions your brain will probably explode Another option how to introduce a variable for later use is to create an empty matrix Matlab assumes that all variables represent two dimensional matrices Therefore a I will generate a variable a of size 0x0 Creating an empty variable may be useful when we do not know the size of the variable up front and let the variable to grow as needed In all other cases we should initialize the variable using zerosxy command as that will allow Matlab to allocate appropriate amount of memory and yields faster code execution datasets The MATLAB statistics toolbox provides a type of matrix called a dataset It is structured like the data are in almost all of the popular GUIdriven statistics packages with named variables in the rows and observations in the columns Operators Operators usually take two inputs and produce one output Plus and minus are probably the first operators you learned at elementary school Relational comparison operators Relational comparison operators compare two values hence the name Importantly they do not destroy or overwrite anything unless combined with an assignment operator The comparison operators are lt gt lt gt and 7 These should be fairly obvious 7 less than greater than less than or equal to etc Note that the double equals sign is not a typo 7 is equal to is a double equals sign this is what distinguishes it from the assignment operator 7 means not in MATLAB so the last one is not equal to Logical Logical operators combine logical values using AND OR NOT and exclusive OR XOR if you ve taken logic out of a philosophy dept congratulations 7 it was not a completely wasted semester They are very useful when we need to determine if a value is within or outside a particular interval as we do in hypothesis testing or to detect outliers The operators are 7 NOT amp AND l OR and Xorvaluel value2 XOR Here is an example X randnlOO 1 This puts 100 normally distributed random numbers with mean 0 and standard deviation 1 in the 100Xl column vector X Y Xlt 2 l Xgt2 This nds each case in which the value is more than 2 standard deviations from the mean In English it reads Set y to TRUE for each value of X that is less than 72 0R greater than 2 The parenthesis ensure that the operations are done in the right order evaluate the less than and the greater than then evaluate the OR just like in high school algebra The resulting variable y is a logical vector of the same size as X containing 0 false wherever X is between 2 and 2 ie within 2 standard deviations from the mean and 1 true wherever the value of X is outside this interval If you need to combine single logical values ie scalars as opposed to vectors use double amp ampamp or double l H ampamp and H are called shortcircuit operators because the second expression is evaluated only if necessary For example if you have only one value in a variable ie tvalue from a comparison of two groups use t lt critivalue ll t gt critivalue to nd if your tvalue is signi cant If the rst expression is true there is no need to evaluate the second expression true OR anything is always true This is useful if you want to avoid generating a warning when the second expression is not de ned for some cases x lengthb0 ampamp meanbgtlOO If b is empty second expression meanbgt100 is not evaluated and warning is Divide by zero is avoided Arithmetic and A should be obvious for single values also called scalars remxy gives the remainder of division xy Colon The colon isn t an operator in the strict sense but I ll introduce it now anyway It stands for through in that 1 5 generates the numbers 1 through 5 More usefully x 1 5 generates the integers 1 through 5 and stores them in the vector x I include it the here because you can think of it as an operator that keeps adding a true operation 1 to the rst number until it gets to the second number You can also specify a different number to use as the increment For example x 10525 generates the sequence 10 15 20 50 and stores it in the variable x Func ons Functions are fancy blackbox versions of operators They take zero or more inputs called arguments and produce one or more outputs called return values In MATLAB sum is a function version of that by default operates on columns sum 2 2 will produce the same output as 22 Because sum and other functions operate on columns by default they can be used as a fast method to generate summary statistics for various data sets Let s say that you have a data set with variables in columns and observations in rows I have accuracy in the first column and reaction time in seconds in the second column for four different participants rows mydata 75 120 88 1310 59 89 72 152 mydata 07500 12000 08800 13100 05900 08900 07200 15200 Now to generate summary statistics for my data I simply call mean and std function on the whole data set and Matlab knows what to do gtgt meanmydata ans 07350 12300 gtgt stdmydata ans 01190 02627 Although it is possible to organize your data in another way using rows for individual observations and columns for different variables will save you a lot of headache Columnoriented analysis of multivariate statistical data is default in both Matlab and other data analysis packages like SPSS Functions are powerful and exible and they are nice in that we usually don t care how they work internally For example let us put some data in a variable y and plot it somedata randn201 plotsomedata 4 gt7 Look at the x axis 7 it seems that the function plot automatically plotted our data as y against and x consisting of the integers l to 20 That won t always be what we want but it is a handy default Now lets create 20 more numbers moredata logspacel2 20 This function creates 20 logarithmically spaced numbers between 10Al 10 and 10A2 100 Now let s plot again plotmoredata somedata This time plot made a graph of the second variable somedata as a function of the first variable moredata How does it know how to behave when it is given one vs two input arguments or how does it know how to deal with one input that is a row vector 20x1 and another that is a column vector 10x1 We don t care All we care about is that it is a black box into which we can throw sensible input and receive in return sensible output No matter what you want to do with MATLAB in the course there is probably a function to do it Here s how easy it is to do a bootstrap replication mydata 50 lOrandn 100 1 bootsamp randsamplemydata 100 true Here randn creates a data set of 100 normally distributed numbers that we scaled to a mean of 50 and a standard deviation of 10 let s say we want to simulate a sample of scores on a Wechsler scale The function randsample then grabs 100 values from mydata with replacement creating one simulated data set Wow randsample seems like it is doing a pretty hard and complicated job for us 7 how does it work Again you don t have to care Think of it like your car as long as it goes when you press the skinny thing on the right and stops when you press the fat thing on the left you or most people at least don t care how it works Cars can be driven by people who aren t mechanics and that makes cars useful for all of us Control flow Control ow refers to the programmers ie your ability to have your program do different things depending on the value of one or more variables Say for example you collected a data set with n20 and computed the mean Now you want to compute a sampling distribution for that mean using 200 bootstrap replications of the experiment What you need to do in English is collect using randsample a bootstrap replication compute the mean store it keep doing the above three steps until 200 replications have been done The key here is that you want your program to do something different when you have collected fewer than 200 replications 7 in this case keep going 7 than you do when you have nished collecting your 200 replications 7 in this case stop There are three basic control structures in MATLAB that should allow you to do everything you need to do for basic Monte Carlo and Bootstrap analysis In fact the rst two we ll discuss should probably suf ce for0 The for statement is what is known as a loop because it allows you to loop through repeat a series of steps for some specified number oftimes For example we might want to compute a bootstrapped sampling distribution of the mean using 200 bootstrapped replications of our experiment Let s create some data to play with data randn 100 Now we have 100 measurements of IQ scores stored in the vector data Next well make a vector to store each sample mean as we go through the loop mybootmeans zeros 200 1 Here we created a variable that will store all our 200 boostrapped sample means We don t have to initialize pregenerate variables in Matlab but it does speed up the code especially when creating larger vectors or matrices Initially each element is set to zero Now we can use for to do the bootstrapping f or i l 20 O onesample randsample data 100 true mybootmeans i meanonesample end The rst line tells MATLAB that we are going to go through whatever is inside the braces 200 times incrementing the value of the variable i each time This is really convenient because we can use i as an index into the vector mybootmeans in order to store each of our 200 bootstrapped means To plot the sampling distribution we can just type hist mybootmeans Step back and think about this 7 we have barely learned to program and we can already compute a bootstrapped sampling distribution of the mean And all we ve had to learn are the functions for sample mean 7 whose function should be obvious 7 and randn to create some fake normally distributed data and hist to look at a histogram of the results Wee haa if0 The if statement behaves just like the word if behaves in our language For example you might think IfI have nished my stats assignment by 10 pm I ll go out A fancier version is If I have nished my stats by 10 pm I ll go out else I ll stay home and get depressed You will use if usually in connection with relational operators when you need to evaluate a certain condition for example when testing a hypothesis if mymeangtcriticalvalue hO false else hO true In Matlab if is often implicit in other commands such as while nd or when using logical indexing We will talk about these later while0 The while control statement repeatedly executes a command or commands while some condition is true Let s say that you would like to generate a random sample of 40 IQ scores but it is important to you that your sample mean and sample standard deviation will be approximately that of population ie 100 and 15 Maybe you need your sample mean to be within 5 points from the population mean and your sample standard deviation within 2 points from the population standard deviation You can automatically generate a sample like that by asking Matlab to keep generating samples until it nds a sample that is suitable generate the initial IQ sample iqsample round15randn40l 100 specify tolerable difference between your sample statistics and population statistics okmeandiff 5 okstddiff 2 test whether your sample statistics are within tolerable limits and keep generating new samples if not while absmeaniqsample lOOgtokmeandiff ll absstdiqsample 15gtokstddiff iqsample round15randn40llOOL After the code nishes the required sample will be in the iqsample variable find and loqical indexinq findO nd enables you to nd indices of all observations that satisfy a condition and is a computationally highly ef cient fast shortcut for a combination of for and if median reaction times in a complex cognitive task myrts 217 131 144 98 126 85 23 157 it is thought that reaction time that involves decision making ie different response to A o0 different kind of events cannot be shorter than 300 400 ms because of the number of synapses involved tooshort findmyrts lt 3 tooshort 7 I should have a closer look at data from participant number 7 logical indexing logical indexing is a great feature of Matlab that makes various common computations fast and elegant It allows you to perform an operation on a subset of your data that satisfy some condition without having to use for if or even nd Let s say you measured spatial awareness in one class of high school students Gender lfemale Z nale is coded in a variable gender spatial awareness score in variable spaw Beside population mean you may wish to compute mean separately for males and females In Matlab you can do this easily in one line of code meanfemmalescore meanspawgender 1 meanmalescore meanspawgender 2 Read compute mean for those values of vector spaw where vector gender has a value of l Data creation Data creation is somewhat of a misnomer Generally we use data creation functions to generate a convenient xaxis or axes An important exception is Monte Carlo analysis in which we use data creation functions to make simulated data sets in order to compute a sampling distribution We have already encountered one important data creation tool which is the operator and is used to generate a sequence of integer values as in x 120 Now the variable vector x contains the integers 1 through 20 You can also specify the increment value in the middle x l 5 2 O which gives us 39 numbers running from 1 to 20 in steps of 05 Another option is the linspace command which allows you to specify the number of points you want rather than the increment So for example if we want 40 points between 1 and 20 rather than an increment of exactly 05 we can enter x linspace l 20 40 A very similar command logspace generates logarithmically spaced numbers x linspacel 20 40 We have already encountered a very simple data creation function which is the way to type in data using square brackets So X 0 l l 2 3 5 8 13 concatenates glues together the 8 values 7 the first 8 numbers in the Fibonacci series 7 into the single vector x You can also concatenate vectors a 1 2 b 3 4 x a b will set xto 1 2 3 4 This is useful for entering very small data sets For larger data sets the functions in input and outpu below are much more useful You can also repeat values or whole matrices using repmat for replicate matrix So x repmat 2 72 20 l is the same as x 272ones20 l and creates a vector of 20 rough approximations to 6 Alternatively x repmat 1 2 3 20 3 creates a 20 x 9 matrix containing 20 rows ofthe sequence 1 2 3 1 2 3 1 2 3 For Monte Carlo analysis MATLAB provides a wonderful corpus of random number generators from which we can draw random samples from various common distributions If we want 100 say random numbers from a standard normal distribution all we have to do is enter x randn 1001 and 7 poof 7 we have our sample If we need 100 normally distributed numbers representing standard IQ scores we can enter x 7 100 15randn1001 which generates 100 normally distributed random numbers with a mean of 100 and a standard deviation of 15 Why be normal For random numbers from a uniform distribution x rand100 1 which generates a uniform at distribution of numbers between 0 and 1 Or if we are studying something like whether subjects are above or below some baseline the binomial distribution might be helpful x binornd50 1 100 1 Which simulates how many times heads came up in 50 ips of a very unfair coin 7 a coin in which heads is expected to come up only 10 ifthe time 7 across 100 experiments Some handy distributions are described below For a complete list of the distributions that MATLAB can generate see supported distributions in MATLAB s help Statistical distributions Statistics toolbox provides a number of buildin distributions for which you can generate random samples rnd probability pdf and cumulative probability cdf density functions inverse functions inv or even fit these functions into your data fit To call the specific function for your distribution of choice simply put together Matlab name of the distribution e g logn for lognormal distribution or bino for binomial distribution with one of the generic function name suffix listed above So lognmd0 15 will give you 5 random numbers from a lognormal distribution with mean 0 and sd l and binocdf11016 will give you probability of maximum of one success eg throwing 6 on a dice out of 10 trials using an unbiased dice What are the most useful distributions depends largely on the field of study but probably include the following beta beta distribution e g for Bayesian statistics gam gamma distribution eg canonical hemodynamic response function in fMRI exp exponential distribution eg radioactive decay norm normal distribution sum of many independent events if it is complicated it is Gaussian logn lognormal distribution product of many independent events wbl weibull distribution eg in psychophysics chiZ chisquare distribution independence of factors goodness of tting f F distribution eg analysis of variance t Student s tdistribution estimating mean for small sample sizes bino binomial distribution e g die rolling and coin ipping pois poisson distribution e g rare events modeling input and output DA TA INPUT AND IMPORT J We have already met the concatenation operator It can be used to manually input a small number of values like this X 1 2 4 8 16 32 64 Ioad0 If you have your data numbers only in a tab delimited text le from Excel or notepad named mydatatxt you can read it into MATLAB by typing x load mydatatxt and 7 poof 7 your data are in MATLAB tucked away in the variable x if the file isn t in MATLAB s current working directory you have to specify the path in addition to the file within the quotes You can also use load mydatatxt no quotes Your data will then be in variable mydata dImreadO Same as above but can be used for files delimited by coma tab or any other delimiter xlsreado For Excel files that have variable names in the first row and numerical values elsewhere use xlsread
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'