Hello I have this code for Game of life now I am getting an error in calculating the num_neighbors. Please help me fix it. Thank you

조회 수: 1 (최근 30일)
mylife = round(rand(size_of_game,size_of_game));
%mylife = [0 0 0 0 0;0 0 0 0 0;0 1 1 1 0;0 0 0 0 0 ;0 0 0 0 0 ];
%%%plot
while 1%for 11 = 1:1000
axis([-size_of_game size_of_game -size_of_game size_of_game])
cla;
spy(mylife)
grid on
%propagate
newlife = mylife;
for ii = 1:size_of_game
si = ii-1;
ei = ii+1;
veci = si:ei;
veci(veci==0)=size_of_game;
veci(veci==size_of_game)=1;
for jj = 1:size_of_game
%%%This is overlap from each side
sj = jj-1;
ej = jj+1;
vecj = sj:ej;
vecj(vecj==0)=size_of_game;
vecj(vecj==size_of_game+1)=1;
num_neighbors =sum(sum(mylife(veci,vecj)))-mylife(ii,jj);
if mylife(ii,jj)
%Any live cell with fewer than 4 live neighbours dies
if num_neighbors <= 4
newlife(ii,jj) = 0;
end
%Any live cell with four or more live neighbors lives on to
%next generation
if num_neighbors > 4
newlife(ii,jj) = 1;
end
end
end
end
drawnow
mylife=newlife;
end

답변 (1개)

Aveek Podder
Aveek Podder 2017년 11월 7일
Hi,
I think you are receiving an "Index exceeds matrix dimensions" error, that is due to the fact that the elements in vector 'veci' is exceeding the 'size_of_game'. This issue can be avoided by changing the roll back condition of 'veci'.
The rollback condition for 'veci' is given below:
veci(veci==size_of_game+1)=1;

카테고리

Help CenterFile Exchange에서 Conway's Game of Life에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by