eightneighbours: Count Number of Neighbours in a Rectangular Cellular Grid.

Description Usage Arguments Value See Also Examples

View source: R/neighbours.R

Description

This function returns the sum of the eight neibours of a cell within a matrix. It can be used to simulate simple cellular automata, e.g. Conway's Game of Life.

Usage

1
2

Arguments

x

The cellular grid, which typically contains integer values of zero (dead cell) or one (living cell).

Value

A matrix with the same structure as x, but with the sum of the neighbouring cells of each cell.

See Also

seedfill, neighbours, conway

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
n <- 80; m <- 80
x <- matrix(rep(0, m*n), nrow = n)
x[round(runif(1500, 1, m*n))] <- 1
## uncomment this for another figure
#x[40, 20:60] <- 1

image(x, col=c("wheat", "grey", "red"))
x2 <- x
for (i in 2:10){
  nb <- eightneighbours(x)

  ## survive with 2 or 3 neighbours
  xsurv <- ifelse(x > 0 & (nb == 2 | nb ==3), 1, 0)

  ## generate for empty cells with 3 neigbours
  xgen <- ifelse(x == 0 & nb == 3, 1, 0)

  x  <- ((xgen + xsurv)>0)
  x2 <- ifelse(x2>1, 1, x2)
  x2 <- ifelse(x>0, 2, x2)

  image(x2, col=c("wheat", "grey", "red"), add=TRUE)
}

Example output

Loading required package: deSolve

simecol documentation built on June 3, 2018, 5:07 p.m.