Certainly! Below is a simple MATLAB code to create a version of Conway's Game of Life, which is a cellular automaton devised by the British mathematician John Horton Conway in 1970.
matlab
function game_of_life
% Define the size of the grid
gridSize = 50;
% Define the initial configuration of the grid
grid = rand(gridSize) > 0.7;
% Create a figure for visualization
h = imagesc(grid);
colormap(gray);
axis equal off;
% Update the grid in a loop
while true
grid = updateGrid(grid);
set(h, 'CData', grid);
pause(0.1); % Pause for 0.1 seconds between updates
end
end
function newGrid = updateGrid(grid)
% Get the size of the grid
[rows, cols] = size(grid);
% Pad the grid with zeros on all sides for easy neighbor calculation
paddedGrid = padarray(grid, [1, 1], 0);
% Initialize new grid
newGrid = zeros(rows, cols);
% Rule implementation
for row = 1:rows
for col = 1:cols
% Count the live neighbors
liveNeighbors = sum(sum(paddedGrid(row:row+2, col:col+2))) - paddedGrid(row+1, col+1);
% Apply the Game of Life rules
if grid(row, col) == 1 % Cell is alive
if liveNeighbors < 2 || liveNeighbors > 3
newGrid(row, col) = 0; % Dies
else
newGrid(row, col) = 1; % Lives
end
else % Cell is dead
if liveNeighbors == 3
newGrid(row, col) = 1; % Birth
end
end
end
end
end
Here's how the code works:
The game_of_life function sets up an initial grid with a random configuration, where each cell has a probability of being alive (value of 1) or dead (value of 0).
The imagesc function is used to visualize the grid as an image, and the colormap is set to gray to clearly show the live and dead cells.
The while true loop continuously updates the grid by calling the updateGrid function and updates the image data.
The updateGrid function takes the current grid as input and returns a new grid after applying the rules of Conway's Game of Life.
To run this simulation, simply copy the code into an .m file in MATLAB and run the game_of_life function. The simulation will run indefinitely, showing the evolution of the grid. You can stop the simulation by closing the figure window or by pressing Ctrl+C in the MATLAB command window.