如何使用 numpy meshgrid 执行 ND 坐标扫描 [英] How to perform an ND coordinate sweep using numpy meshgrid

查看:63
本文介绍了如何使用 numpy meshgrid 执行 ND 坐标扫描的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 4 维采样点网格.我希望点从 0 到 10,每个方向的间距相等.我尝试了几次 np.meshgrid 调用的迭代,但我确信我做错了什么.创建这些点的正确方法是什么?

I want to create a grid of sampling points in 4 dimensions. I want the points to span from 0 to 10 with equal spacing in each direction. I tried a few iterations of np.meshgrid calls, but I am sure I am doing something wrong. What is the proper way to create these points?

import numpy as np
XL, XU = (0, 10) # lower/upper bounds
MD = 4 # 4 dimensions
x = np.linspace(XL, XU, 20)
np.meshgrid(*[x for ____ in range(MD)])[0].reshape(MD, x.size ** MD // MD).T

array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       ...,
       [10., 10., 10., 10.],
       [10., 10., 10., 10.],
       [10., 10., 10., 10.]])

我目前最好的解决方案有重复的元素,所以我确定我一定做错了什么.这里出了什么问题?如何创建所需的等距点网格?

My current best solution has repeated elements, so I'm sure I must have done something wrong. What has gone wrong here? How can I create the desired grid of equally spaced points?

推荐答案

meshgrid 返回相应数组中的坐标.在您的情况下,有 4 个维度:

meshgrid returns the coordinates in the corresponding arrays. In your case for 4 dimensions:

xx, yy, zz, ww  = np.meshgrid(x, y, z, w)

这意味着,xx 将包含所有 x 坐标,而 yy 将包含所有 y 坐标等等.进一步xx.shape == yy.shape == ... 并且等于网格上的点数.

That means, xx will contains all the x coordinates while yy all the y coordinates and so on. Further more xx.shape == yy.shape == ... and is equal to the number of points on the grid.

为了得到你想要的结果,可能是stack:

To get your desired result, might be stack:

# point as rows 
out = np.stack(np.meshgrid(*[x]*MD), axis=-1).reshape(-1, MD)

array([[ 0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.52631579],
       [ 0.        ,  0.        ,  0.        ,  1.05263158],
       ...,
       [10.        , 10.        , 10.        ,  8.94736842],
       [10.        , 10.        , 10.        ,  9.47368421],
       [10.        , 10.        , 10.        , 10.        ]])

# or point as columns
out = np.stack(np.meshgrid(*[x]*MD).reshape(MD, -1)

array([[ 0.        ,  0.        ,  0.        , ..., 10.        , 10.        , 10.        ],
       [ 0.        ,  0.        ,  0.        , ..., 10.        , 10.        , 10.        ],
       [ 0.        ,  0.        ,  0.        , ..., 10.        , 10.        , 10.        ],
       [ 0.        ,  0.52631579,  1.05263158, ...,  8.94736842,  9.47368421, 10.        ]])

这篇关于如何使用 numpy meshgrid 执行 ND 坐标扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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