home *** CD-ROM | disk | FTP | other *** search
- %LIFE MATLAB's version of Conway's Game of Life.
- % Demonstrates sparse matrices and Handle Graphics.
-
- % C. Moler, 7-11-92, 8-7-92.
- % Copyright (c) 1984-93 by The MathWorks, Inc.
-
- fig = clf;
- clc
- echo on
-
- % "Life" is a cellular automaton invented by John Conway that involves
- % live and dead cells in a rectangular, two-dimensional universe.
- % In MATLAB, the universe is sparse matrix which is initially all zero.
-
- m = 101;
- X = sparse(m,m);
-
- % Press any key to continue after pauses.
- pause
-
- clc
-
- % The initial population for this demonstration consists
- % of a "blinker" and two "gliders".
-
- p = -1:1;
- blinker = [0 1 0; 0 1 0; 0 1 0];
- glider = [0 1 0; 1 1 0; 1 0 1];
- k = 40; X(k+p,k+p) = blinker;
- k = 51; X(k+p,k+p) = glider;
- k = 69; X(k+p,k+p) = glider;
-
- % The following statements plot the initial configuration.
- % The "find" function returns the indices of the nonzero elements.
-
- [i,j] = find(X);
- figure(fig);
- plothandle = plot(i,j,'.','erasemode','background','markersize',12);
- axis([0 m+1 0 m+1]);
-
- pause
-
- clc
-
- % Whether cells stay alive, die, or generate new cells depends
- % upon how many of their eight possible neighbors are alive.
- % Here we generate index vectors for four of the eight neighbors.
- % We use periodic (torus) boundary conditions at the edges of the universe.
-
- n = [m 1:m-1];
- e = [2:m 1];
- s = [2:m 1];
- w = [m 1:m-1];
-
- pause
-
-
- clc
- % The computation is concisely written in a second M-file, lifeloop.m.
- type lifeloop
- pause
- clc
-
- % The progress of the simulation is controlled by t and tfinal.
- % Initially,
-
- tfinal = 0;
- t = 0;
-
- % The variable t is incremented in the inner loop.
- % The value of tfinal is changed by four pushbuttons.
- % See life.m for the details.
-
- % Click "Step" to set tfinal to t+1 and get one step.
- % Click "Go" to set tfinal to inf and initiate an infinite loop.
- % Click "Stop" to set tfinal to t and terminate the loop.
- % Click "Done" to make tfinal negative and clear the figure.
-
-
- echo off
-
- on = 'set(gohandle,''back'',''cyan''); ';
- off = 'set(gohandle,''back'',''default''); ';
- figure(fig);
- stephandle = uicontrol('position',[100 5 50 25],'string','step', ...
- 'callback',[on 'tfinal = t+1; lifeloop; ' off]);
- gohandle = uicontrol('position',[170 5 50 25],'string','go', ...
- 'callback',['if finite(tfinal),' on 'tfinal = inf; lifeloop; end'], ...
- 'interruptible','yes');
- stophandle = uicontrol('position',[240 5 50 25],'string','stop', ...
- 'callback',[off 'tfinal = t;']);
- donehandle = uicontrol('position',[310 5 50 25],'string','done', ...
- 'callback',[off 'tfinal = -1; clf']);
-
- echo off
-