Как суммировать значение соседей в матлабе?

Я новичок в Matlab и пытаюсь кодировать игру жизни. Но у меня есть некоторые трудности с суммированием соседей. Каждая ячейка может иметь значение 0 или 1. Я пытаюсь использовать счетчик (как в Python, единственная программа, с которой я немного знаком), но это не работает. Проблема в том, что это должно работать для всех ячеек, а также для граничных ячеек. Если у меня есть значение каждой ячейки (чтобы оно было где-то между 0 и 8), я должен реализовать правила. Но я также не знаю, правильно ли это. Пожалуйста помоги! Я впадаю в отчаяние!

TIME = 50;


pulsar;

life = {};  % create list 'life'
life{1} = X;  % add seed to life

numrows = size(X,1); % calculate number of rows
numcolumns = size (X,2);  % calculate number of columns

current = X;            % make seed the first current(matrix you're starting off with in each step)

for i = 0:TIME;    % determine amount of times the loop will run 

for row = 1:numrows;              % for each row
    for column = 1:numcolumns;    % for each column

 if column + 1 ~= numcolumns + 1
 east_of_row = column + 1;  % define how to count the cell right of target cell
 end
 if column - 1 ~= 0
 west_of_row = column - 1; % define how to count the cell left of target cell    
 end
 if row - 1 ~= 0
 north_of_column = row - 1; % define how to count the cell north of target cell    
 end
 if row + 1 ~= numrows + 1
 south_of_column = row + 1;
 end

  neighbors = 0                               % start counter 'neighbors' with 0

            if current(row,east_of_row) == 1;              % if neighboring cell has a value of 1
                neighbors = neighbors + 1;                                  % add 1 to neighbors
            end
            if current(row,west_of_row) == 1;              % if neighboring cell has a value of 1
                neighbors = neighbors + 1;                                  % add 1 to neighbors
            end
            if current(north_of_column,column) == 1;       % if neighboring cell has a value of 1    
                neighbors = neighbors + 1;                                  % add 1 to neighbors
            end
            if current(south_of_column,column) == 1;       % if neighboring cell has a value of 1    
                neighbors = neighbors + 1;                                   % add 1 to neighbors
            end
            if current(south_of_column,east_of_row) == 1;  % if neighboring cell has a value of 1
                neighbors = neighbors + 1;                                   % add 1 to neighbors
            end
            if current(north_of_column,east_of_row) == 1;  % if neighboring cell has a value of 1
                neighbors = neighbors + 1;                                  % add 1 to neighbors
            end
            if current(north_of_column,west_of_row) == 1;  % if neighboring cell has a value of 1
                neighbors = neighbors + 1;                                  % add 1 to neighbors
            end
            if current(south_of_column,west_of_row) == 1;  % if neighboring cell has a value of 1
                neighbors = neighbors + 1;                                   % add 1 to neighbors     
            end


        % rules of the game:

    if current(row,column) == 1;              % in case a target cell has a value of 1:

        if neighbors < 2                           % if the number of neighbors is smaller than 2
            nextnext(row,column) = 0;                   % value of target cell gets 0 in nextnext
        end
        if neighbors == 2                      % if the number of neighbors is 2 or 3
            nextnext(row,column) = 1;                   % value of target cell stays 1 in nextnext
        end
        if  neighbors == 3
            nextnext(row,column) = 1;
        end
        if neighbors > 3                        % if the number of neigbors is higher than 3
            nextnext(row,column) = 0;                   % value of target cell gets 0 in nextnext
        end
    end
    if current (row,column) == 0           % in case a target cell has a value of 0:

        if neighbors == 3                          % if the number of neighbors is 3
            nextnext(row,column) = 1;                   % value of target cell gets 1 in nextnext
        end
        if neighbors ~= 3                       % if the number of neigbors isn't 3
            nextnext(row,column) = 0;                  % value of target cell stays 0 in nextnext
        end
end
    end
end


current = nextnext;       % make nextnext matrix the current matrix for the next step 
%life{TIME} = nextnext;    % add matrix to list 'life

end



show(life);

person user2162627    schedule 13.03.2013    source источник
comment
Ваш код довольно длинный, не могли бы вы немного подробнее объяснить, какая часть представляет проблему и в чем именно заключается эта проблема? Например, вы получаете какие-либо сообщения об ошибках?   -  person Dennis Jaheruddin    schedule 13.03.2013
comment
@DedekMraz Хорошая находка. Я не удосужился проверить (удалил свой ответ, чтобы не допустить дублирования без принятого ответа).   -  person Eitan T    schedule 13.03.2013
comment
@EitanT твоя матрица маски выглядела знакомо. На самом деле нашел аналогичный подход (и маску) в другом вопросе.   -  person Dedek Mraz    schedule 13.03.2013
comment
На данный момент я получаю сообщение об ошибке, потому что 'west_of_row' не определено в if current(row,west_of_row) == 1. Я действительно не понимаю, почему, потому что я думал, что определил его на пару строк выше этого.   -  person user2162627    schedule 13.03.2013


Ответы (1)


Вы можете использовать conv2 для вычисления этого значения следующим образом:

%First create some example matrix 
%  (this is a 5 x 5 matrix with 30% 1's, 70% 0's
x = full(ceil(sprand(5,5,0.3)))

%Create your convolution kernal
%    This will add up all the values in the 8 elements surrounding the
%    central element
k = [1 1 1; 1 0 1; 1 1 1];  

%Now do the copnvulution (using the 'same' argument to select an output
%the same size as the input.)
counts = conv2(x,k,'same')

Это будет каждый раз создавать немного другой пример. Но для одного выполнения приведенного выше кода я получаю следующее:

x =
     0     1     0     1     0
     0     1     0     1     0
     0     0     1     1     0
     0     1     0     1     0
     0     0     0     0     0

counts =
     2     1     4     1     2
     2     2     6     3     3
     2     3     5     3     3
     1     1     4     2     2
     1     1     2     1     1
person Pursuit    schedule 13.03.2013
comment
Я должен использовать только основные операции из poiwerpoints, которые я получил от своего учителя, conv2() там нет. - person user2162627; 13.03.2013