### Create a StudySoup account

#### Be part of our community, it's free to join!

Already have a StudySoup account? Login here

# Peer Advising CIS 410

UO

GPA 3.84

### View Full Document

## 17

## 0

## Popular in Course

## Popular in Computer & Information Science

This 95 page Class Notes was uploaded by Dahlia Rutherford DVM on Tuesday September 8, 2015. The Class Notes belongs to CIS 410 at University of Oregon taught by Staff in Fall. Since its upload, it has received 17 views. For similar materials see /class/187244/cis-410-university-of-oregon in Computer & Information Science at University of Oregon.

## Similar to CIS 410 at UO

## Reviews for Peer Advising

### 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/08/15

CIS 410510 Computational Data Science Introduction to OctaveMatlab Matthew Sottile matt cs uoregon edu University of Oregon Department of Computer and Information Science April 9 2008 I Abrii 9 2008 a1 95 Computational Platform During the course we will approach analysis tasks from two sides computational methods and their mathematical basis For the computational side we will work within a powerful analysis framework that is easy to use and highly portable The tool of choice will be Octave the open source clone of the commercial tool Matlab o Octave is not a perfect replica of Matlab in open source form It differs in some important ways at the language level but for the most part in a way that is easy to notice when moving between the tools I H April 9 2008 2 95 Acquiring Octave Octave is available for all major platforms Windows MacOSX and Linux Two sites are of interest for acquiring Octave 0 http www octave org This is the primary home page for Octave and you can download the sources and binaries here 9 http octave sourceforge net This is the home of Octaveforge a project that aims to provide functionality equivalent to the add on toolboxes that you buy for Matlab This is very useful April 9 2008 3 95 Tool overview These tools are summarized by the following key features 0 They provide an interpreted environment You don39t worry about memory management or low level programming 0 Algorithms are expressed in a data parallel form Code can be easier to read by working with whole arrays instead of nests of loops 0 Underneath the interpreter are very mature robust rich and fast numerical libraries such as BLAS LAPACK FFTW and so on So the tools are good for rapid prototyping while achieving reasonable performance H April 9 2008 4 95 Alternative tools Other tools exist and are good for similar tasks but have different strengths than OctaveMatlab Those in red are open source while the others are commercial A non exhaustive list 0 GNU R Statistical computation o Mathematica Symbolic computation and programming 0 Maxima Symbolic computation and programming 0 Maple Symbolic computation and programming a SPSS Statistical computation A nice aspect of these tools is that they all are similar in how they treat data and arrays so once you39ve tackled the learning curve with one the others become simpler to pick up I H April 9 2008 5 95 What about insert tool here There are other tools that have some level of following lately such as numerical add ons to Python and Ruby or more rudimentary tools like Excel or other spreadsheets o The scripting languages PythonRuby should be avoided for numerical analysis for two big reasons 0 Their performance is unpredictable 9 The various numerical tools were designed in isolation from each other so interfaces representations and other conventions are inconsistent and potentially confusing I was very disappointed with Python in real applications a Spreadsheets are exceptionally useful for small scale data analysis and plotting but ill suited to complex analysis of extremely large data sets ill April 9 2008 6 95 Octave Features 0 Array manipulation and computation language Interpreted with automatic memory management Based on optimized numerical libraries that can take advantage of vector hardware eg MMX SSE AltiVec and lately multicore processors Integrated visualization tools Portable across platforms Capable of reading a huge range of standard data formats Extensible with C plugins Very rich set of build in functions and algorithms April 9 2008 195 Vectors matrices and tensors A vector is a one dimensional sequence of numbers For example coordinates of a point in 2D are composed of two numbers for each dimension X and y Vectors of length n are known as n dimensional vectors A matrix is a two dimensional set of numbers An MXN matrix has M rows and N columns A tensor is a higher dimensional generalization of a matrix A 3d cube of numbers is a tensor We will most commonly illustrate examples with vectors and matrices simply because higher dimensional structures are a bit harder to visualize 1 and 2 dimensions are easier to illustrate I ll April 9 2008 8 95 Vectors matrices and tensors This terminology is important In computer science we most often think about arrays asjust arrays blobs of data that can be indexed with one or more indices By naming instances of arrays ie 1D array is a vector 2D array is a matrix etc we can draw a connection between the computational representation of a structure nD blob of numbers and the semantic meaning of the data being represented The mathematical tools we will use will often be defined based on the semantic meanings matrix vs vector vs tensor and we will want to be able to mentally connect this semantic meaning to a representation within the computer I ill 7 April 9 2008 9 95 Semantics vs syntax You will often hear me refer to things as being a semantic definition versus a syntactic definition What do these mean a Syntax The syntax of something is the representation of a concept without any specific context For example given an array X the syntax Xi corresponds with the ith element of the array X o Semantics The semantic meaning of something is the meaning in the context in which it is being discussed For example if I have an array of N numbers the syntactic description is simply the list of numbers while the semantic meaning might be a velocity vector39 There is an important distinction here Syntax tells you how something is represented Semantics tell you how to interpret it So a set of numbers is syntacticallyjust a set of numbers but semantically could be interpreted as describing a velocity I ll April 9 2008 10 95 Arrays The array is the fundamental structure for representing data and performing computations octave73001gt A1 2 3 A The array is the programming language representation of mathematical structures like vectors matrices and tensors Api ll 9 2008 3911 1 95 Arrays The previous slide showed an array as a row vector You can also represent arrays as columns This distinction is necessary when you will later apply linear algebra operations using array data octave73002gt A1 2 3 A 7 M Api ll 9 2008 3912 1 95 Arrays We aren39t restricted to 1D vectors Arrays can be 2 or more dimensions to represent matrices and tensors octave73003gt B1 2 3 4 5 6 7 i AM 9 2008 13 95 Array storage Arrays in Octave are stored in column major order This means that the array B1 2 3 4 5 6 is stored in memory as 1 4 2 5 3 6 This is the order that Fortran uses Arrays in C on the other hand are stored in row major order So in C the array B would be stored in memory as 1 2 3 4 5 6 This is very important to remember because sometimes we will want to access the data in a 2 or more dimensional array as though it was a 1D array so the element ordering should be known W Column major Row major I H April 9 2008 14 95 Array element access We can access elements individually by addressing them by their coordinates In 2D Octave specifies the row first then the column This is convenient as this is how matrix indices are generally specified octave73003gt B1 2 3 4 5 6 B octave 730O4gt B2 1 ans 4 Beware lndices in Octave start at 1 not zero I H April 9 2008 1595 Array dimensions Matrices are given dimensions M by N or MXN where M is the number of rows and N is the number of columns We can ask an array what it39s dimensions are with the size command octave 730013gt size B ans AM 9 2008 3916 95 Array dimensions The size command gives us the number of distinct indices in each dimension in the same order that we use to index elements Arrays generalize to higher dimensions also As mentioned earlier Octave is a data parallel language What does this mean I April 9 2008 17 95 Whole array operations A data parallel language allows you to perform wholearray operations very succinctly Say we want to add 10 to all of the elements of an array We can do this without any loops octave73001gt B12 3 4 5 6 octave73002gt CB1O C 11 12 13 14 15 16 TIP Following a command with a semicolon suppresses output to the console You will want to do this when you are writing scripts to prevent lots of output I ll April 9 2008 18 95 Whole array operation pitfalls We have to be careful when using operators that have different meanings depending on their context In Octave the multiplication operator can mean element wise multiplication or matrix multiplication Say we multiply an array by a scalar octave73001gt B12 3 4 5 6 octave73003gt 82 ans 6 8 10 12 This worked But what if the right side of the is another array that we want to multiply against element wise I ill April 9 2008 19 95 Whole array operation pitfalls octave73003gt B1 2 3 4 5 6 octave73004gt C3 2 1 6 5 4 octave73005gt BC error operator 2 nonconformant arguments opl is 2x3 op2 is 2x3 error evaluating binary operator 39 nearulineu5ucolumnu2 We get an error Looking closely it is because B is 2x3 and C is 2x3 and Octave read the as meaning matrix multiplication Matrix multiplication requires that the number of columns in the left side is the same as the number of rows on the right side so we see an error But we didn39t want matrix multiply in the first place How do we fix this I 39 April 9 2008 20 95 Matrix operations What is the difference Remember matrix multiplication Given an MXN matrix A and an NXP matrix B we define their product C AB as N CU 2AM BM v e 1Mj e 1 P k0 What we were actually looking for was simpler Given the MXN array A and some constant k we simply want to produce a new array C defined as C0quot kAij VI E 17 M 17N April 9 2008 2195 Element wise whole array operations Prefacing operators like and quot with a dot will tell Octave that we really wanted element wise operations not matrix operations octave73001gt A1 2 3 octavei3002gt B9 8 7 octave73003gt AB ans 9 16 21 24 25 24 I Aphl 9 2008 22 95 Slice notation Sometimes we want to extract portions of an array to work on instead of the whole array We can use what are known as array slices or sections to achieve this A slice is expressed in the form first last first stride last The indices are assumed to start at index 1 If the length is unknown you can use the keyword and as the last index to include the last element April 9 2008 23195 Slice notation Examples lndices1234 last 24 lndices 234 14 lndices1234 2end lndices 234 last 327 lndices 3 5 7 4 11 lndices 4321 Think of slices as a way of specifying a set of indices that you want to access simultaneously We can specify a slice for each dimension Let39s go through some examples with a real array April 9 2008 24 95 Slice examples Consider the following large array octave73005gt A12 3 45 6 7 8 91011 12 1314 15 16 A 1 2 3 4 5 6 7 8 9 10 11 12 3 14 15 16 TIP Sometimes you want to split a long command across multiple lines In Octave and Matlab you must use the line continuation string April 9 2008 25 95 Slice examples With slices we can extract rows columns or blocks of data from the array octave73008gt A3 ans octave73009gt A 3 ans 11 15 I Apm 9 2008 2 5 95 Slice examples octavei30010gt A23 23 ans ans m 3 7 V ADM 9 2008 21 95 Slice examples octave730012gt A124 224 ans 2 4 10 12 Visualizing array sections 123456 123456 123451 Dungeon I mmwa k mmng k 123456 123456 123453 mUIbOONK mmng l Top row A A3 A3 Bottom row A23 A13 A1324 Matthew Sottlle uo IS 39 Aprll 9 2008 29 95 Slice examples You can also use slice notation to treat data of 2 or more dimensions as 1D data This is where the column versus row major distinction comes into play octave73001gt A12 3 4 5 6 octavei3002gt A39 ans TIP The single quote 7 is used to get the transpose of a matrix Above we use it to turn a column vector NX1 into a row vector 1XN to fit on the slide April 9 2008 30 95 Applying array notation We can now start to do interesting things with arrays even without seeing loop syntax yet Consider an array X of length n where we want to approximate the derivative using a simple differencing scheme X X1 7 X for each i E 17 n 71 octave73001gt X1 3 2 2 4 5 9 octavei3002gt Xp X2end7X1end71 Xp 2710 214 April 9 2008 3195 Array notation and index sets Slice notation is really defining index sets An index set is simply the set of indices that a statement refers to The colon notation can be used outside the array index context to generate arrays containing the values described by colon notation Aoctave 73001gt A128 A Obviously end has no meaning here nor does the colon on it39s own Those only make sense in the context of array indexing I ll April 9 2008 32 95 Shifts Sometimes you want to generate an index set that corresponds to circularly shifting the array by a certain amount in a given dimension The shift function provides this Consider the following array octavei30070gt A1 2 3 4 5 6 A 789 12 3 4 5 6 7 8 9 How does this look as we shift it around in different ways April 9 2008 33 95 Shifts octave73007lgt shift A1 ans 7 8 9 1 2 3 4 5 6 octave730072gt shift A71 ans 4 5 6 7 8 9 1 2 3 The term circular shift captures the wrapping around we see as rows shift off the top or bottom and reappear on the other side I Apm 9 2008 3A 95 Shifts octave730073gt shiftA12 ans 3 1 2 6 4 5 9 7 8 octave730074gt shift A712 ans 2 3 1 5 6 4 8 9 7 We can shift on any dimension with the third parameter default is 1 AM 9 2008 I 3595 Common arrays Sometimes it39s useful to be able to create arrays with specific contents with a single command You can create an MXN array of zeros with the command zerosMN An array full of ones can be created with the command onesMN You can create an identity matrix a matrix with ones down the main diagonal zeros elsewhere with the command eyeMN April 9 2008 36 95 Common arrays octave 730O2gt zeros3 2 ans O O O O O O octave73003gt ones32 ans AM 9 2008 31 95 Common arrays octave73007gt eye5 5 ans OOOOH OOOl O OOl OO Ol OOO I OOOO If the dimensions do not match up rows or columns of zeros will be used to fill in the extra rows or columns For example eye65 will have zeros only in the 6th row I Apnl 9 2008 38 95 Common arrays The randO command can be used to create arrays populated with random values The values are uniformly distributed on the interval 01 octave 73004gt Xrand3 4 021014 093997 097893 082185 085073 076130 082121 082480 041470 071996 035784 051396 randn rande randp and randg can be used to generate random numbers drawn from Normal Exponential Poisson and Gamma distributions I ill April 9 2008 39 95 Sparse arrays A sparse array is an array in which the vast majority of elements are zero Given that most elements are zero it is wasteful to store all elements explicitly in memory there is a great deal of wasted space Sparse formats are focused on storing only the non zero elements If an array is sufficiently sparse ie 90 of the elements are zero the storage savings from a sparse versus dense representation can be significant I April 9 2008 A0 95 Sparse arrays rows 10000 cos octave 73004gt X rows 10000 cos 1234 5678 7gt Compressed Column Sparse octave 73002gt X12345678 octave 73003gt X12344444 Compressed Column Sparse 1234 4444 7gt 42 octave 73001gt Xsparse1000010000 nnz 0 32 42 nnz 2 I 1 Apr 9 2008 4195 Array constructors We sometimes want to create arrays out of simpler ones For example we might wish to create a matrix where all rows or columns are repeated instances of a single vector The repmatO command can be used to accomplish this octave730025gt X1 2 3 4 X 1 2 3 4 octave730026gt repmatX3 1 ans I ill April 9 2008 42 95 Array constructors The second argument to repmat is a row vector representing the number of times we want the array replicated in each dimension octave730025gt X1 2 3 4 1 2 3 4 octave730027gt repmatx3 2 ans Apni 9 2008 A3 95 Avoiding loops When programming in Matlab or Octave avoid loops at all costs and express as much as possible in array notation Why These tools get their performance by invoking library routines under the covers that are optimized to work on arrays as whole chunks So most of the computational time is spent in the computational routines not the interpreter Loops are implemented in the interpreter which is much slower than the highly optimized libraries under the covers Implicit loops via slice notation yields reliably good performance 7 April 9 2008 44 95 Connection with real languages It is interesting to note that Matlab and Octave are most closely related to the Fortran family of languages The original Matlab was essentially a scripting version of Fortran intended to target libraries like BLAS and LAPACK Matlab evolved as did Fortran The slice notation and many other features of the Octave and Matlab are shared with Fortran 90 and later 11 tquot w Matthew Sottile UO CIS Computational Data Science Lllilll Loops Sometimes you just need a loop The practice of converting loops to array or vector notation is often called vectorization This was a programming practice that was examined a great deal in the 1980s during the domination of vector supercomputers such as the Crays in the science world What was a key discovery at that time Some algorithms just don39t vectorize Loops cannot be avoided for all algorithms So how do we use them in Octave April mugs 45 95 Loop syntax For loops have the form for indexstartstridefinish body end While loops have the form while booleaniexpression body end TIP Comments in Octave start with the character AM 9 2008 AT 95 Loop syntax An example for loop Add up the odd numbers between land 100 sum 0 for i12100 sum sum i end Ap39H 9 2008 V 45 95 Loop syntax An example while loop Approximate log base 2 the really silly way l 0 X 2048 while X gt1 l l1 X X2 end a t I Ap39rllQQQOB 49 95 Transcending loops So what sorts of techniques exist to express algorithms without loops Simple loops are easily implemented with data parallel operations consider example earlier of adding 10 to all elements of an array What if the body of the loop did more complex work One common method for dealing with this in Octave and Matlab is the use of mask arrays Mask arrays are the result of applying logical operations to arrays Let39s see a couple examples April 9 2008 50 95 Boolean operations Identify all elements in an array greater than 50 octavei30020gt rfoorrand2 10100 r 38 18 10 73 71 48 98 38 52 26 14 4 50 87 38 79 59 64 5 4O octave730021gt mask r gt 50 mask O O O 1 1 O 1 O 1 O O O O 1 O 1 1 1 O O I Apm 9 2008 5195 Masking We can use the mask and element wise multiplication to preserve only those values that we care about octavei30022gt rmask ans 7 O O O 73 71 O 98 O 52 O O O O 87 O 79 59 64 O O I Apnlg 2008 52125 Masking Now say we want to do something like updating an array such that elements less than or equal to 50 stay the same and values greater than 50 are reduced by 50 In loopy code this might look like for i1sizer1 for j1sizer2 if rij gt 50 r011 rI J50 end end end April 9 2008 53195 Masking For the first step let39s modify the elements that are greater than 50 This is pretty easy in data parallel notation octave 730024gt r750mask ans 70 70 70 23 21 70 48 70 2 70 70 70 O 37 70 29 9 14 70 70 Ignore the 0 elements for now Apriignoos 5495 Masking Now we want to combine the modified values that were selected using the mask with those that were not modified to produce the final result This is pretty easy by creating a new mask representing all of the values turned off in the existing mask octave 730028gt mask mask I ll AWll 9 2008 55 95 Masking Bringing it all together octave 730030gt r 38 18 10 14 4 50 octave 730031gt ans 38 18 10 14 4 50 73 87 71 38 48 79 98 59 38 64 52 5 r750mask rmask 0 23 37 21 38 48 29 48 9 38 14 2 5 26 40 40 AM 9 2008 5695 Find A useful command often used in conjunction with masks is the find command Let39s try it out How about we extract all of the elements in an array greater than some value In this case a 3X3 random array where we want values greater than 07 octave 730038gt rrand 3 3 r 0022942 0818191 0673446 0294057 0612661 0895059 0593759 0945446 0997296 I ll April 9 2008 57 95 Find We can see the mask and corresponding find output octave 730042gt maskrgt07 mask 0 1 0 0 0 1 0 1 1 octave 730043gt findmask39 ans Remember the find command works on the linearized version of the array and arrays are stored in column major order I H Aprii 9 2008 58 95 Find So given that find is generating an index set we can use it to extract the elements octave 730045gt rfind mask39 ans 081819 094545 089506 099730 octave 730046gt rfind mask 39 ans 0022942 0294057 0593759 0612661 0673446 Apni 9 2008 59 95 Conditional syntax Conditionals are often necessary also generally in the form of quotif then else blocks Testing for more than one possible condition can be achieved with the elseif clause if booleaniexpression quotthenquot body elseif booleaniexpression elsef quotthenquot body else quotelsequot body end Apnl 9 2008 60 95 Built in functions Octave has a large number of basic functions that provide common operations for you A few of the more useful 0 sumXd Compute the sum of elements along dimension d If d is not specified d 1 assumed a maXXd minXd Compute the maximum or minimum value along dimension d 0 mod eXp abs floor ceil sin cos tan asin acos atan sqrt Element wise operations that do what they say 0 who List the set of variables in memory 0 clear Clear out the set of variables in memory clear X clears specified variables leaving others untouched a help cmd Provide documentation on how to use the specified command This will be your best friend starting off I ll Aprilg 2008 6195 Built in functions octave730054gt r1 2 3 4 r l 2 3 4 octave 730055gt sum r ans octave 730056gt sumr 2 ans AM 9 2008 6295 Plotting One can argue that the most useful thing about Octave and Matlab next to the interpreted language is the ability to easily and quickly plot data Visual inspection of data especially large data sets is very important for understanding your data and the effect of computations on it This is one area where Octave and Matlab differ pretty significantly Octave is far more limited with respect to plotting than Matlab For simple applications such as those we will use in this class it should suffice So let39s see an example How about plotting sinX for X in 07 87139 I ll April 9 2008 63 95 Plot example m Gnuplnt 05 39 o 39 39 05 71 100 150 200 572999 0295999 octave 30075gt plotsin OO18 pi r39 April 399 2008 64 95 Matthew Sottil Plotting The plot command can be pretty complex Refer to help plot for detailed documentation For the most part you will use plot in the following forms a plotX Plot the values of the array X Octave will draw the points connected by lines here a plotX3939 Plot the values of the array X as points represented with 3939 symbols No lines connecting the points 0 plotX39r39 Similar to the previous but instead of using the default blue color plot the 3939 symbols in red You can plot multiple data sets by holding the plot window between plot commands I H April 9 2008 65 95 Plot example A Flgure 1 cquot 71 108 87 70326526 octave 30021gt XOIO1I8 pi octave 30022gt plotsinx octave 30023gt hold on octave 30024gt plotsin05x r octave 30025gt hold off Matthew Sottile UO CIS Cainpura hal Dar April 9 2008 66 95 Plotting points Iquot 39 h w Cnupim on 02 0202585 0585952 We can also provide X and Y coordinates to plot 2D points octave 30022gt Yrand1100Xrand1100 octave 30023gt plotXY Matthew Sottile UO CIS Coinpura bhal Dar If April 9 2008 67 95 Plotting What happens if you pass in a 2D array for plotting The plot command will plot each column individually lfwe39re dealing with 2D data though this isn39t very useful The image and surf commands are much more informative here Let39s create a test data set first that we can use to make images octave730058gt Xy ndgrid72pi0252pi octave730059gt imsinxsiny The array contains the value of sinx siny over the square ranging over 7271397 27139 in both the X and Y dimension by steps of I ill April 9 2008 58 95 ndgrid What is that ndgrid command doing In this case were using it to generate two arrays of coordinates The ijth element of X contains the X coordinate of the point and of Y contains the Y coordinate octave73001gt Xy ndgrid722 X i2 i2 i2 i2 i2 71 71 71 71 71 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 I Aprii 9 2008 69 95 y 72 71 0 1 2 72 71 0 1 2 72 71 0 1 2 72 71 0 1 2 72 71 0 1 2 This is useful when we want to do computations that require coordinate sets m 3 7 i I AM 9 2008 70 95 2d plots You can plot 2D arrays as images using the image command The colorbar command is used to give a reference to what values the colors correspond to s e e w Gnupinl 10 965128 238858 2d plots The choice of color scheme can be important in how one perceives the variations in the data The colormap command is used to select these color schemes Here is the same data set in gray m Figure 1 2d plots What do the commands look like that produced the figures on the previous slides octave730058gt Xy ndgrid72pi0252pi octave730059gt imsinxsiny octave730060gt imageimcoorbar octave730061gt figure imageimcoorbar octave730062gt colormapgray TIP You must use the figure command to open a new plotting window to prevent plots from being overwritten The close command is used to close windows close closes the most recent window to have focus close all closes all of the open plotting windows I ll April 9 2008 73 95 Surface plots Sometimes looking at the data from a 3D point of view gives some insight into it39s structure The surf command can be used to look at data as a surface octavei30058gt Xy ndgridi2pi 0252pi octave730059gt imsinxsiny octavei30060gt surfim I Apni 9 2008 74 95 Surface plots n n r w gure 1 0120 050000 310000 scale 100000 100000 a Writing functions So far everything has been written straight to the interpreter command line This is good for testing out ideas but at some point we will want to encapsulate complex computations in reusable functions First let39s see how to encapsulate code in a function Functions take zero or more inputs and produce zero or more outputs Given a function FOO we will usually create a file called F00m that contains the code for the function Octave and Matlab both tend to follow the one function per file pattern For helper functions that are used only by one caller one can embed the helpers in the same file as the function that uses them The caveat is that these helper functions are not callable from the outside I ll AWll 9 2008 75 95 I 7H Writing functions Let39s define a function that we will call WORKER that takes two arrays as the argument and returns the sum of the elements in the first the second and in the elementwise ratio of the two function sx sy sr WORKERXY sx sumX sy sumY sr sumXY To invoke this we must either move to the directory containing WORKERm using the Cd command or add the directory to the Octave search path using the addpath command Aprii 9 2008 77 95 Writing functions DC DC B C 0C CUgto A tave730012gt Xrand15 Yrand15 tave730013gt ABC WORKERXY 13246 24155 11081 tave730014gt Xrand15 Yrand15 tave730015gt ABC WORKERXY 25639 15180 35916 You should notice that Octave is case sensitive Make sure your cases make sense if you get unexpected errors that something you expect to eX I ist is not being found Aprii 9 2008 78 95 Bringing it all together Given what we have learned let39s write something interesting One of my favorite examples Conway39s Game of Life The game of life is really easy We start with a 2D array populated with ones and zeros where a one corresponds to alive and a zero to dead We repeatedly apply a simple rule that states a If any element of the array has less than 2 or more than 3 neighbors that are alive it dies of loneliness or starvation 0 Live cells with 2 or 3 neighbors stay alive 0 Dead cells surrounded by 3 cells come to life I H April 9 2008 79 95 Game of Life 0 4mm 2mm 1855M 39 b Mm Am 9 2m an g5 Counting neighbors We can use the shift operation to count up the neighbors We need to look at eight shifts to count neighbors to the left right up down left up right up left down right down Illustrated here are the shifts with the circularity shown as spilling into a border region Matthew Sottile UO CIS April 939 2008 81 95 Shifts to count neighbors sum shiftworld1 l shiftworld7l shiftworld12 l shiftworld712 shiftworld112 l shiftshiftworld7112 l shiftshiftworld1712 l shiftshift 712 world 71 Now we know for every cell how many neighbors it has assuming the world is a torus both topbottom and leftright wrap around Applying the update rule is now very simple I ll April 9 2008 82 95 T 7 e update rule 0 sum gt 1 Number of cells with 2 or more neighbors a sum lt 4 Number with 3 or less 0 sum gt 1 sum lt 4 Number with 2or 3 0 sum gt 1 sum lt 4 world Number alive with 2 or 3 a sum3 Cells with precisely 3 neighbors 0 sumgt1 sumlt4world sum3 Combine o gt O All cells that must remain on will have non zero values world sum gt1 sum lt 4 world i sum gt0 April 9 2008 83 95 All together function goln iters thresh world randnn gt thresh for i1iters imageworld colormapgray drawnow sum shiftworld1 l shiftworld71 shiftworld12 l shiftworld7l2 shiftshiftworld112 l shiftshiftworld7l shiftshiftworld1712 shiftshiftworld7l7l2 sum gt1 sum lt 4 sum3gt0 world l drawnow forces the image to be drawn allowing us a rudimentary animation I l Aprll 9 2008 8495 More array manipulations We saw how to go from an nD array to a 1D one using the colon How do we go the opposite direction The reshape command octave730010gt X floorrand11810 X 624540263336521339 octave730011gt reshapex3 6 ans M 4 0 no N no I H Aprii 9 2008 85 95 Reshaping You must ensure that the product of the array dimensions matches the length of the array A shape mismatch error results if they do not octave730013gt reshapex3 7 error reshape size mismatch This function comes in useful pretty often One example is where you have stored a multi dimensional array in a file as a sequence of numbers You can load them in as a 1D array and given that you know the intended dimensions use reshape to give the data the proper shape I ll April 9 2008 86 95 Rotation and flipping There are builtin functions for rotating arrays and flipping them about their different dimensions For rotation we have two functions rotQO and rotdim rotQO works on 2D arrays only The first argument it takes is the array to rotate and the second optional argument is the number of times to rotate the array in the counter clockwise direction by 90 degrees Negative numbers correspond to clockwise rotation rotdim is a generalized version of rotQO that takes a third argument corresponding to the dimension for rotation Routines to flip arrays are also available For 2D flipud and fliplr flip about the horizontal and vertical axes respectively For arbitrary dimension flipdim is available I ll AWll 9 2008 87 95 Rotation and flipping x octavei30015gt X1 2 3 4 1 2 3 4 octave 730016gt rot90x ans 7 V ADM 9 2008 88 95 Accessing external data Finally we get to the last topic on Octave and one highly relevant for this class How do we get data into and out of Octave There are a few different ways depending on the type of data that you are dealing with We will consider a Text data 0 Binary data 0 Image data a Specialized data formats April 9 2008 89 95 Text data Text data is assumed to be numerical data stored in a plain ASCII format This can be a sequence of numbers one per line or on a single line separated by spaces or tab characters If a text file has multiple lines containing multiple elements per line the data file is treated as though it was a matrix The load command is used to load data For example say the file datadat has our data octave 730024gt X load 39data dat 39 Octave does not natively support CSV files often exported from tools like Excel Make sure to choose space or tab as your delimiter I Tll April 9 2008 go 95 Binary data Many data acquisition devices provide data in a raw binary format such as 32 or 64 bit integers or IEEE floating point values In other cases for storage efficiency binary is used to generate files smaller than their ASCII equivalent Octave provides a set of routines based on C IO such as freadO for this purpose 0 Files are opened with fopenO 0 Data is read using freadO 0 Data is written using fwriteO 0 Files are closed with fcloseO Refer to the help pages for these for details such as the set of supported data types I H April 9 2008 9195 Image data Images are loaded and written using the functions imreadO and imwriteO These are not built in functions In Matlab they are a part of the Image Processing Toolbox ln Octave they are part of the Octave Forge project They can be installed using the OctaveForge pkg command You can download the Image package from the OctaveForge web site Assuming the tar file is called image 1XXtargz and resides in the directory homeusersname you can execute the following to install it octave73001gt cd homeusersname octave73002gt pkg install imageilxxtargz This has not been tested by me on Windows or Linux Please refer to your installation documentation first before using pkg I 39l April 9 2008 92 95 Specialized formats One of the most useful formats for storing data you generate within Octave is the native Octave binary format This format stores the set of variables you have created in Octave on disk You can exit Octave and come back later and restore your state This is also useful for saving intermediate results that you would like to be able to roll back to in case you make an error The save command is used for this and the load command is used to restore the data Note that there is also a related format that Matlab uses The save and load commands support various versions of the Matlab format for interoperability between the tools I Tll April 9 2008 93 95 Octave native 02gt 03gt octave 730 octave 730 X12 3 4 5 y5 4 3 21 octave73004gt save myfilemat X octave73005gt clear octave73006gt X error X39 undefined near line 6 column 1 06gt load myfilemat 07gt dispx octave 730 octave 730 1 2 3 4 5 octave73008gt dispy error y39 undefined near line 8 column 6 error evaluating argument list element number 1 TIP The disp command prints the value of a variable This is the preferred method instead of simply leaving the semicolon off of commands I April 9 2008 9495 HDF The final format we will care about is the Hierarchical Data Format or HDF from The University of Illinois National Center for Supercomputing Applications HDF is a common format for storing data produced by simulations It allows for data to be stored with metadata related to how it should be interpreted HDF is also nice because being a standardized format with rich metadata other tools can read data in HDF format with no knowledge of how it was produced and interpret it For example visualization tools can be used to look at complex data sets using HDF HDF is supported by the load and save commands See the help pages for them if you require HDF access I ll AWll 9 2008 95 95

### BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.

### 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'

## Why people love StudySoup

#### "There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

#### "Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

#### "I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

#### "It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

### Refund Policy

#### STUDYSOUP CANCELLATION POLICY

All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email support@studysoup.com

#### STUDYSOUP REFUND POLICY

StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here: support@studysoup.com

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to support@studysoup.com

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.