对于矩阵中的每个元素,找到其所有邻居的总和 [英] For each element in a matrix, find the sum of all of its neighbors

查看:68
本文介绍了对于矩阵中的每个元素,找到其所有邻居的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个矩阵,我想找到每个元素的邻居之和(所以结果是一个矩阵).邻居是给定元素上方,下方和旁边的值(如果存在)(不考虑对角线元素).

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).

示例:

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

预期结果是:

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

在不使用循环的情况下在R中执行此操作的最简单方法是什么?

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

推荐答案

一种方法是与每一侧的邻居建立矩阵并将它们加在一起.

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

这篇关于对于矩阵中的每个元素,找到其所有邻居的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆