Matlab-周围元素的总和 [英] Matlab - Sum of surrounding elements
问题描述
我想计算矩阵中给定元素周围的元素总和.到目前为止,我已经编写了以下几行代码:
I want to calculate the sum of the elements surrounding a given element in a matrix. So far, I have written these lines of code:
for i=1:m,
rij(1:n)=0
for j=1:n,
alive = tijdelijk(i-1,j)+tijdelijk(i+1,j)+tijdelijk(i-1,j-1)+tijdelijk(i+1,j-1)+tijdelijk(i,j+1)+tijdelijk(i,j-1)+tijdelijk(i-1,j+1)+tijdelijk(i+1,j+1)
这会导致错误,因为例如对于i = 1,i-1变为零.任何人都知道如何做到这一点,而不会出现此错误?
This results in an error because, for example, i-1 becomes zero for i=1. Anyone got an idea how to do this without getting this error?
推荐答案
您可以通过过滤对元素求和. conv2
可以用于这种方式.
You can sum the elements via filtering. conv2
can be used for this manner.
让我举个例子.我创建了一个样本矩阵
Let me give an example. I create a sample matrix
>> A = reshape(1:20, 4, 5)
A =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
然后,我创建一个过滤器.过滤器就像一个遮罩,将中心放在当前单元格上,并且将与过滤器上1's
对应的位置相加.对于八连接的邻居,过滤器应如下所示:
Then, I create a filter. The filter is like a mask where you put the center on the current cell and the locations corresponding to the 1's
on the filter are summed. For eight-connected neighbor case, the filter should be as follows:
>> B = [1 1 1; 1 0 1; 1 1 1]
B =
1 1 1
1 0 1
1 1 1
然后,您只需将矩阵与这个小矩阵卷积即可.
Then, you simply convolve the matrix with this small matrix.
>> conv2(A, B, 'same')
ans =
13 28 48 68 45
22 48 80 112 78
27 56 88 120 83
18 37 57 77 50
如果需要四个连接的邻居,可以将过滤器的角设为0.类似地,您可以根据自己的目的设计任何过滤器,例如对所有邻居求平均值而不是求和.
If you want four-connected neighbors, you can make the corners of your filter 0. Similarly, you can design any filter for your purpose, such as for averaging all neighbors instead of summing them.
有关详细信息,请参阅Wikipedia中的卷积文章.
For details, please see the convolution article in Wikipedia.
这篇关于Matlab-周围元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!