Array Correlation - compute array difference with its neighbor elements

2 次查看(过去 30 天)
Hi,
Do you know the fastest way to compute array mean difference with its neighbor elements in a N x N matrix? and is there a possibility to perform for second neighbors, third and so on.
Suppose you have
a=[1 4 5 3 6 ; 8 10 0 9 11 ; 2 5 20 15 9 ; 8 12 4 6 0 ; 7 9 18 2 5]
so I want a code to give this result for mean difference of first neighbors:
d(1,1)=[(1-4)+(1-8)]/2, d(1,2)=[(4-1)+(4-5)+(4-10)]/3, d(2,2)=[(10-8)+(10-0)+(10-4)+(10-5)]/4 and etc. For second neighbors: dd(3,3)=[(20-2)+(20-9)+(20-5)+(20-18)/4].
thank you

回答(1 个)

Walter Roberson
Walter Roberson 2017-10-29
mask = [0 1 0; 1 0 1; 0 1 0];
Ncount = conv2(ones(size(a)), mask, 'same');
d = double(a) - conv2(double(a), mask, 'same')./Ncount;
You can leave out the double() if you are sure that a will not be integer data type (images are usually integer data type.)
For second difference, use an appropriate larger mask such as
[0 0 1 0 0; 0 0 0 0 0; 1 0 0 0 1; 0 0 0 0 0; 0 0 1 0 0]
  2 个评论
ichi
ichi 2017-10-30
Thank you for the answer, I knew the conv2(a,mask,'same'), gives you the sum of the neighbors of each element, but this method is so good.

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by