MATLAB: How to sum all adjacent elements in a matrix with 1’s and 0’s

conv2matrix

i'm looking for a way to sum all adjacent elements in a matrix with 1's and 0's. so [ 1 0 1; 1 0 0; 0 0 0] would give the following matrix: [ 1 3 0; 1 3 1; 1 1 0]. for n x n matrices there already was a solution: conv2(MyMatrix, ones(n), 'same'). i'm very curious if this also works with m x n matrices (m ~= n) and how it works. Thanks!

Best Answer

MyMatrix = [1 0 1 0; 1 0 0 1; 0 0 0 1]; %your m x n matrix, m ~= n
msk = [1 1 1; 1 0 1; 1 1 1];
z = conv2(MyMatrix, msk, 'same')
z =
1 3 1 2
1 3 3 2
1 1 2 1