MATLAB: Help finding sum of adjacent elements and creating matrix of the sums.

matrixmatrix indexmatrix sum

So basically I have a 3 x 3 matrix of 1s and 0s, and I want to create another 3×3 matrix which has the sum of the adjacent (including diagonal) values for each element that is 0, and display 5 for each element that is 1.
For example, given the matrix
I =
0 0 1
1 0 1
0 1 0
I'd want to create the sum matrix that looks like this:
C =
1 3 5
5 4 5
2 5 2

Best Answer

  • Try conv2():
    theSum = conv2(yourMatrix, ones(3), 'same');
    I recommend not using single letter variables because it can be confusing once your program gets larger and larger. Plus I looks a lot like 1 (one) and l (lower case L).
    [EDIT] Regarding your edit:
    yourMatrix = [...
    0 0 1
    1 0 1
    0 1 0 ]
    theSum = conv2(yourMatrix, ones(3), 'same');
    % Special condition to set theSum = 5
    % if the value of yourMatrix == 1
    theSum(yourMatrix == 1) = 5
    Results in the command window:
    yourMatrix =
    0 0 1
    1 0 1
    0 1 0
    theSum =
    1 3 5
    5 4 5
    2 5 2