开发者社区> 问答> 正文

将2D数据分组为x,y中的重叠圆圈

我目前正在处理一个相当大的3D点数据集(x,y,z),并想要一种有效的方法来识别xy平面中一组圆内的哪些点,半径为r和中心(x1,y1) ),其中x1和y1是网格坐标(每个长度为120)。圆圈将重叠,某些点将属于多个圆圈。

因此,输出将是14400个圆(120 * 120)的标识,并且(x,y,z)列表中的哪个点在每个圆中。

import numpy as np

def inside_circle(x, y, x0, y0, r):

return (x - x0)*(x - x0) + (y - y0)*(y - y0) < r*r

x = np.random.random_sample((10000,))
y = np.random.random_sample((10000,))

x0 = np.linspace(min(x),max(x),120)
y0 = np.linspace(min(y),max(y),120)

idx = np.zeros((14400,10000))
r = 2
count = 0

for i in range(0,120):

for j in range(0,120):
    idx[count,:] = inside_circle(x,y,x0[i],y0[j],r)
    count = count + 1

其中inside_circle是一个函数,它为半径为r的圆中的每个测试点x,y,z给出一个布尔值为True或False的数组,其中心为x0 [i]和x0 [j]

我的主要问题是,是否有一种比嵌套for循环更有效的方法?

展开
收起
一码平川MACHEL 2019-01-23 17:19:09 2130 0
1 条回答
写回答
取消 提交回答
  • 这个使用数组广播,比嵌套的for循环稍快(在我的机器上0.5s vs 0.8s)。在我看来,可读性有所下降。

    import numpy as np

    x = np.random.random_sample((1, 10000))
    y = np.random.random_sample((1, 10000))

    x0 = np.reshape(np.linspace(np.min(x),np.max(x),120), (120, 1))
    y0 = np.reshape(np.linspace(np.min(y),np.max(y),120), (120, 1))

    r = 2

    all_xdiffssquared = np.subtract(x, x0)**2
    all_ydiffssquared = np.subtract(y, y0)**2

    3d here means that the array has 3 dimensions. Not the geometry described

    all_xdiffssquared_3d = np.reshape(all_xdiffssquared, (120, 10000, 1))
    all_ydiffssquared_3d = np.reshape(np.transpose(all_ydiffssquared), (1, 10000, 120))
    all_distances_3d = all_xdiffssquared_3d + all_ydiffssquared_3d - r**2
    idx = np.signbit(np.reshape(np.moveaxis(all_distances_3d, 1, -1), (14400, 10000)))

    2019-07-17 23:26:46
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
重新定义计算的边界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载