Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each element in a matrix, find the sum of all of its neighbors

Tags:

r

matrix

Given a matrix, I want to find the sum of the neighbors for each element (so the result is a matrix). The neighbors are the values above, below and beside the given element ,if they exist (not considering the diagonal elements).

Example:

> z = matrix(1:9, 3, 3, byrow=T)
> z
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

And the expected result is :

> result
     [,1] [,2] [,3]
[1,]    6    9    8
[2,]   13   20   17
[3,]   12   21   14

What is the simplest way I can do this in R without using loops?

like image 671
Goutham Avatar asked Mar 22 '14 03:03

Goutham


1 Answers

One way would be to make matrices with the neighbor on each side and add them together.

rbind(z[-1,],0) + rbind(0,z[-nrow(z),]) + cbind(z[,-1],0) + cbind(0,z[,-ncol(z)])
##      [,1] [,2] [,3]
## [1,]    6    9    8
## [2,]   13   20   17
## [3,]   12   21   14
like image 151
Aaron left Stack Overflow Avatar answered Oct 08 '22 04:10

Aaron left Stack Overflow