MATLAB: Game of Life Help

forgame of lifehelpMATLABwhile loop

Hi. I'm making Game of Life in MATLAB and I feel stuck now as I don't know how to program past second generation.
Here's my code that takes the input (ginput) on the board and then, after the input is done, makes some calculations to determine if one and each cell is going to survive or if it is going to die. The terms are: if there are no living cells in one point and there are 3 neighbors then a new cell is born in next generation.
An already living cell stays alive if it has 2 or 3 living neighbors, otherwise it dies.
Now here's the code I got so far that makes so I can click on the board and mark where I want my cells to begin and then when I push Enter I see the next generation. Then when i push Enter again, the board closes and the program is over.
The help I need is to go 50 generations forward with the same principes and a small pause between generation shifts on the board. I have tried while loop but it doesn't seem to serve my purpose.
Thanks in advance for your help.
CODE:
% Game of Life
n=40;
figure(1), clf
fill([1 n+1 n+1 1],[1 1 n+1 n+1],'w')
axis equal, axis([1 n+1 1 n+1])
hold on
for k=1:n+1
plot([1 n+1],[k k])
plot([k k],[1 n+1])
end
V=zeros(n,n);
Vny=zeros(n,n);
while 1
[i,j,Knapp]=ginput(1);
i=floor(i); j=floor(j);
if Knapp==1
V(i,j)=1;
fill([i i+1 i+1 i],[j j j+1 j+1],'k')
else
break
end
end
s=0;
for i= 1:n
for j = 1:n
gr=raeknagrannar(V,i,j,n); %A separate function that counts neighbors for each cell
if V(i,j)==0 & gr==3
Vny(i,j)=1;
fill([i i+1 i+1 i], [j j j+1 j+1],'k')
end
end
end

Best Answer

Ahmed - you can use a for loop for your 50 iterations. Just do
for k = 1:50
for i= 1:n
for j = 1:n
gr=raeknagrannar(V,i,j,n); %A separate function that counts neighbors for each cell
if V(i,j)==0 & gr==3
Vny(i,j)=1;
fill([i i+1 i+1 i], [j j j+1 j+1],'k')
end
end
end
V = Vny; % <--- presumably you want to set with the updated board (?)
pause(0.5); % <--- pause for half a second
end
Related Question