The Game Of Life
%GameOfLife.m
size = input('Enter a size: ');
M =
round( rand( size, size ) );
n = 1;
while 1
N = neighbors( M );
M = (~M & N == 3 ) | (M & ( N == 2
| N == 3)) | ...
M.*~(M & ( N < 2 | N > 3 ));
spy( M, 'b*' );
n = n + 1;
title(['Generation ', num2str( n )]);
pause( 0.02 );
end
function
[ N ] = neighbors( M )
%NEIGHBORS Returns a matrix whose individual elements
are the number of neighbors of the
% corresponding element
in its input (0-1) matrix.
N = shiftleft(M) + shiftright(M) + shiftdown(M) + shiftup(M) + ...
shiftdown(shiftleft(M))
+ shiftup(shiftleft(M)) + shiftdown(shiftright(M)) +
...
shiftup(shiftright(M));
function
M = shiftdown( M )
%SHIFTDOWN Returns the input matrix with its rows
shifted down by one position, with wrapping.
M = M( [end 1:end-1], : );
function
M = shiftup( M )
%SHIFTUP Returns the input matrix with its rows
shifted up by one position, with wrapping.
M = M( [2:end 1], : );
function
M = shiftleft( M )
%SHIFTLEFT Returns the input matrix with its columns
shifted left by one position, with wrapping.
M = M(:, [2:end, 1]);
function
M = shiftright( M )
%SHIFTRIGHT Returns the input matrix with its columns
shifted right by one position, with wrapping.
M = M(:, [end, 1:end-1]);