是否有一种更有效的方法来生成numpy中的距离矩阵

编程入门 行业动态 更新时间:2024-10-07 02:19:29
本文介绍了是否有一种更有效的方法来生成numpy中的距离矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道在给定矩阵的H x W和起始索引位置的情况下,是否存在更直接,更有效的方法来生成距离矩阵.

I was wondering if there is a more straight forward, more efficient way of generating a distance matrix given the H x W of the matrix, and the starting index location.

为简单起见,让我们以起始点为(0,0)的3x3矩阵为例.因此,要生成的距离矩阵为:

For simplicity lets take a 3x3 matrix where the starting point is (0,0). Thus, the distance matrix to be generated is:

[[ 0. 1. 2. ] [ 1. 1.41421356 2.23606798] [ 2. 2.23606798 2.82842712]]

索引(0,1)距离为1,而索引(2,2)距离为2.828.

Index (0,1) is 1 distance away, while index (2,2) is 2.828 distance away.

我到目前为止的代码如下:

The code I have so far is below:

def get_distances(start, height, width): matrix = np.zeros((height, width), dtype=np.float16) indexes = [(y, x) for y, row in enumerate(matrix) for x, val in enumerate(row)] to_points = np.array(indexes) start_point = np.array(start) distances = np.linalg.norm(to_points - start_point, ord=2, axis=1.) return distances.reshape((height, width)) height = 3 width = 3 start = [0,0] distance_matrix = get_distances(start, height, width)

我认为这已经非常有效了.但是numpy总是用我通常不会想到的一些技巧使我感到惊讶,因此我想知道在这种情况下是否存在这种技巧.谢谢

This is pretty efficient already, I think. But numpy always surprise me with some tricks that I usually never think of, so I was wondering if there exist one in this scenario. Thanks

推荐答案

您可以使用hypot()进行广播:

import numpy as np x = np.arange(3) np.hypot(x[None, :], x[:, None])

或outer方法:

np.hypot.outer(x, x)

结果:

array([[ 0. , 1. , 2. ], [ 1. , 1.41421356, 2.23606798], [ 2. , 2.23606798, 2.82842712]])

计算网格上每个点到固定点的距离(x, y):

to calculate the distance between every point on a grid to a fixed point (x, y):

x, y = np.ogrid[0:3, 0:3] np.hypot(x - 2, y - 2)

更多推荐

是否有一种更有效的方法来生成numpy中的距离矩阵

本文发布于:2023-11-29 02:21:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有一种   矩阵   方法来   更有效   距离

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!