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)
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?
There are lots of things you can do at the edges. Which you do depends very specifically on your problem and is different from usage case to usage case. Typical things to do:
Since your code mentions "your teacher" I'd guess that you can ask what should happen at the edges (or working it out in a sensible manner may well be part of the task!!).
Two possibilities : change the limits of the loops to
i=k:(m-k)
andj=k:(n-k)
or use blkprocex :
You can sum the elements via filtering.
conv2
can be used for this manner.Let me give an example. I create a sample matrix
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:Then, you simply convolve the matrix with this small matrix.
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.
For details, please see the convolution article in Wikipedia.