Matrix Average of neighbour values

30 views (last 30 days)
After creating a matrix of order MxM it will then output a new matrix in which each element is calculated from the original matrix by finding the average of each element adjacent (horizontally, vertically, excluding diagonal elements) to the original element including the element itself.
For example
then matrix is
�(1,1) = (1 + 2 + 6 )/ 3 = 3
(1,2) = (1 + 2 + 3 + 5 ) /4 = 3
  1 Comment
Kiwala Martin
Kiwala Martin on 19 Feb 2020
I have tried using :
Result = conv2(M, ones(3), 'same')./conv2(ones(3),ones(3), 'same')
But this approach includes the diagonal neighbours, how can i exclude them.
Thanks in advance

Sign in to comment.

Accepted Answer

Marta G
Marta G on 19 Feb 2020
I think using conv2 was a great idea. However, you should use it like this
aa=[0 1 0;1 1 1;0 1 0];
conv2(matrix, aa, 'same')./conv2(ones(DIM),aa, 'same')
This way of convolution does not account for diagonal neighbours. Afterwards, if you do not want decimals, use ceil or round depending on your desire.
Hope this helps :)
Kiwala Martin
Kiwala Martin on 19 Feb 2020
Edited: Kiwala Martin on 19 Feb 2020
Thank you very much Marta.
This has been very helpful.

Sign in to comment.

More Answers (0)


Find more on Operating on Diagonal Matrices in Help Center and File Exchange


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!