Help finding the sum of neighboring elements in a matrix?

36 次查看(过去 30 天)
For a lab I'm supposed to find the sum of the eight elements that are all eight directly horizontal, vertical, or diagonally adjacent to it. Then, I'm supposed to output the sum into a vector that displays values of 0 or 1 in the form of a matrix if it is true based on further details in the lab (if > 5 true if < 5 false). Does anyone have any idea how to do this? I'm fairly new at Matlab... Thank you in advance!
  1 个评论
Jan
Jan 2013-7-25
Do you mean the sum of 9 elements in 3x3 blocks? Should the blocks overlap for the output? Could you provide example data for a 4x4 matrix?

请先登录,再进行评论。

回答(1 个)

Evan
Evan 2013-7-25
编辑:Evan 2013-7-25
A 2D convolution should work for your purposes:
help conv2
To sum elements, just make your filter a matrix of ones. You size will depend on what size "neighborhood" of values you want to add together. So, if you wanted to find the sum of every element within 2 of each element, you would use a 5x5 filter:
M = magic(9); %some data
f = ones(5); %filter
s = conv2(M,f,'same');
The 'same' argument will be important to you here, because it lets you return only the part of the convolution that is the size of your original matrix. This means that the outer values that result from the padding by the convolution function will be trimmed off.
Here's another example that perhaps makes it easier to see. My matrix is a 9x9 matrix of all ones, and my filter is a 3x3 filer also of ones. This shows how many neighbors each element has (the -1 to remove the value contributed by the element itself):
M = ones(9);
f = ones(3);
s = conv2(M,f,'same') - 1;

标签

Community Treasure Hunt

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

Start Hunting!

Translated by