给定大小为 n 的矩阵,计算距中心的距离矩阵

2023-12-02

假设我有一个大小为 n(非 1 的奇数)的矩阵,我想计算每个条目距中心的距离。例如,如果 n = 2,则矩阵为 5 x 5,要找到矩阵的中心,您需要执行以下操作:

import numpy as np
import math
center = math.floor(5/2)
Matrix[math.floor(5/2)][math.floor(5/2)] = 0

The center is zero because the distance to itself is 0. my approach is make the center like the origin of a coordinate plane and treat each of the 25 "squares" (5 by 5 matrix) as a dot in the center of each square and then calculate the euclidean distance that dot is from the center. visually: enter image description here

到目前为止我的想法..

Matrix = [[0 for x in range(n)] for y in range(n)] #initialize the n by n matrix
for i in range(0, n):
    for j in range(0, n):
        Matrix[i][j] = ...

或者有更好的方法来找到距离矩阵吗?

输出应该是对称的,对于 n = 5 矩阵,它是

Matrix
[[2.82843, 2.23607, 2, 2.23607, 2.82843],
 [2.23607, 1.41421, 1, 1.41421, 2.23607],
 [2, 1, 0, 1, 2],
 [2.23607, 1.41421, 1, 1.41421, 2.23607],
 [2.82843, 2.23607, 2, 2.23607, 2.82843]]

TIA


答案就是毕达哥拉斯著名的定理:https://www.mathsisfun.com/pythagoras.html对于 (i,j) 处的单元格,您需要到中心单元格的 (x,y) 偏移量 - 然后应用毕达哥拉斯定理来计算到该单元格的距离...

def pythag(a, b):
    return math.sqrt(a*a + b*b)

n = 5
import math
center = math.floor(n/2)
for i in range(0, n):
    for j in range(0, n):
      dist = pythag(i-center, j-center)
      print(dist)

这是代码的 repl:https://repl.it/@powderflask/DizzyValuableQuark

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

给定大小为 n 的矩阵,计算距中心的距离矩阵 的相关文章

随机推荐