MATLAB Answers

Game of life code

41 views (last 30 days)
Katara So
Katara So on 20 Jan 2021
Answered: Geoff Hayes on 8 Feb 2021
I haven't had much experience with Matlab and want to construct the "Game of Life" but I'm having trouble getting started. I want to write a function which gives the position of a cell or an empty place and gives the number of living neighbors to that cell. I've tried to look around on the Internet to find something that might help me but everything that I find seems to be too advanced. I want a function like:
function neighbors = numneighbors(M,i,j) % where M = matrix of size NxN
If I for example make M = [ 0 1 0 1 1 1 ; 0 1 0 1 0 1 ; 1 1 0 1 0 0 ] (or is there some way of constructing a random matrix of ones and zeros?)
How could I write the function?
All help is appreciated!

Answers (1)

Geoff Hayes
Geoff Hayes on 8 Feb 2021
Katara - if you wish to construct a random matrix of zeros and ones, then you could use randi as
numRows = 10;
numCols = 12;
gameBoard = randi(2, numRows, numCols) - 1;
You could then use conv2 to determine the sum of the neighbouring live cells (i.e the number of living neighbours) for each cell in your game board like
liveCellCounts = conv2(gameBoard, [1 1 1; 1 0 1; 1 1 1], 'same');
This differs from the function signature that you have provided, but you may be able to adapt either this code for the function, or change the function altogether. The code to update the game board given the number of live neighbouring cells could be simplified to 2-3 lines depending upon your rules to update the population.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!