|
"Asif ":
Hi..! Yesterday afternoon I saw your message. It seems interesting to me and this morning I wrote this:
function [m_alives m_deads] = alives(m)
%
[rows columns] = size(m);
m_a = zeros(rows+2,columns+2);
m_a(2:rows+1,2:columns+1) = m; %m ampliated with zeros all around
%%%%%% THE TRICK %%%%% (see <help circshift>)
m_alives = circshift(m_a,[ 0, 1])+... % left neighbors alives
circshift(m_a,[-1, 1])+... % left&lower neighbors alives
circshift(m_a,[-1, 0])+... % lower neighbors alives
circshift(m_a,[-1,-1])+... % right&lower neighbors alives
circshift(m_a,[ 0,-1])+... % right neighbors alives
circshift(m_a,[ 1,-1])+... % right&upper neighbors alives
circshift(m_a,[ 1, 0])+... % upper neighbors alives
circshift(m_a,[ 1, 1]); % left&upper neigbors alives
%%%%%%%%%%%%%%%%%%
m_alives = m_alives(2:rows+1,2:columns+1); % truncating to the interest region
%
% m_neighbors: matrix with total neighbors.
% It should be a better (shorter) form to do it:
% Inner members have 8 neighbors:
m_neighbors = 8.*ones(rows,columns);
% Border members have 5 neighbors:
m_neighbors(1,:) = 5; m_neighbors(rows,:) = 5;
m_neighbors(:,1) = 5; m_neighbors(:,columns) = 5;
%Corners members have 3 neighbors
m_neighbors(1,1) = 3;
m_neighbors(1,columns) = 3;
m_neighbors(rows,1) = 3;
m_neighbors(rows,columns) = 3;
%And finally:
m_deads = m_neighbors - m_alives;
I hope you like it...! Now, you could explain to me, what do you want this for?
|