Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - Sum of surrounding elements

Tags:

sum

matlab

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?

like image 223
user2089012 Avatar asked Dec 08 '22 17:12

user2089012


2 Answers

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

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

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.

like image 193
petrichor Avatar answered Dec 22 '22 02:12

petrichor


Two possibilities : change the limits of the loops to i=k:(m-k) and j=k:(n-k) or use blkproc

ex :

compute the 2-D DCT of each 8-by-8 block

I = imread('cameraman.tif');
fun = @dct2;
J = blkproc(I,[8 8],fun);
imagesc(J), colormap(hot)
like image 28
lucasg Avatar answered Dec 22 '22 04:12

lucasg