Write.gif(storage, filename, col="jet", delay=5) # writing the results into an animated gif Storage <- storage/max(storage) # scaling the results # - this is in order to make the animation prettier # note that I am storing the array of Ni values. # filename - name of the animated gif file # side - side of the game of life arena (matrix) Also, make sure to install the caTools library. Note that you may run out of memory if you specify a very large array. See the code below for how it is actually done. My solution only hides the iteration process by using the R-optimized form of matrix operations and logical subscripting. Also note that in reality the processor does actually iterate through all grid cells the solution presented here does not make all of the iterations happen at the same time. You can write like: vector (BOARDSIZE,vector (BOARDSIZE,DEAD)) Also,the boolean logic of determining the fate of each cell can be enclosed in a function.As these are not changed once the object is initialized. In MatLab you would do this by using the the shift function and so your code would be even simpler. 2.BOARDSIZE, dead and alive can be consts. In R this implementation works MUCH faster than any looping solution. In the next step you use logical subscripting to apply the rules of GoL (conditional on the array of Ni values) to the original array. Next, you stack all of the copies (âsum them upâ using the + operator in R) and this will give you a new array of Ni values.Ä¥. Then you do similar thing with copies 5-8 but now you shift these by 1 position diagonally. So you are essentially shifting the copies of the original array by 1 position to the left, right, up and down.Ä£. â In copy 4 you delete the row at the bottom and add a row of zeroes to the very top. â In copy 3 you delete the uppermost row and add row of zeroes to the bottom. â In copy 1 you delete the leftmost column and add column of zeroes to the very right. What you first need to do is to make 8 copies of the original array. However, iterating through all cells i would take ages in R. Once you know Ni, you change the state of the focal cell i accordingly (to 0 or to 1 using the rules of GoL). You need to figure out what is the number Ni of living cells in the neighborhood of each focal cell i.Ä¢. You have an rectangular array (matrix) of living (1) and dead (0) cells. He suggested to make GoL in R fast by taking the advantage of the somewhat optimized matrix operations. ![]() A couple of years ago my friend Martin Weiser came with an idea to avoid the individual iterations. Cellular automata in R are usually painfully slow if you iterate through all grid cells in an array. Here I demonstrate a simple way to code Conwayâs game of life (GoL) in R and to produce the animation above.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |