MATLAB: Game of Life – the elements don’t die, only grow!

artificial lifegame of lifeif statement

My Game of life program creates some cool patterns, but isnt working as i had hoped.
When i put in a glider pattern as the starting population, the patterns grow infinitely, not transitioning across screen as they should. Something must be wrong with my if statements that should control the elements 'dying.' My code is as follows:
matrix = zeros(500,500);
pop =[1,1,1;1,0,0;0,1,0];
matrix(250:252,250:252) = pop; %puts the initial population in the center of the matrix
while true
imshow(matrix);
k = [1 1 1;1 0 1;1 1 1];
neighbours = conv2(matrix, k,'same');
for row = 1:size(matrix, 1)
for col = 1:size(matrix,2)
if((matrix(row,col) == 1) && (neighbours(row,col)==2||3)) ||((matrix(row,col) == 0) && (neighbours(row,col)==3))
matrix(row,col) = 1;
else
matrix(row,col)=0;
end
end
end
end
thanks for your help

Best Answer

Have a closer look at your logic operations:
neighbours(row,col)==2||3
which is not an error, but it does not do what you think it does!. That line is actually equivalent to this (note the grouping parentheses that I added for clarity):
(neighbours(row,col)==2) || 3
which because all non-zero values are considered true is equivalent to
(neighbours(row,col)==2) || true
which is clearly equivalent to
X || true
which is equivalent to
true
Your mistake was to ignore the clearly documented operator precedence, which states clearly the priorities of the two operators that you are using:
"8. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=)"
...
"12. Short-circuit OR ()"
TIP: check your code as you write it. Read the documentation for each operation that you are using. Do not move on to the next line until you have tested and confirmed that the line does what you need it to do.