具有numpy的网格的可变维数 [英] Variable dimensionality of a meshgrid with numpy

查看:69
本文介绍了具有numpy的网格的可变维数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个n维的网格. 有比使用我正在使用的if子句更好的方法来调用带有n个列向量的meshgrid吗?

I try to create a meshgrid with n dimensions. Is there a nicer way to call meshgrid with n column vectors than with the if clause I am using?

目标是将其用于用户定义的n(2-100),而无需编写100个if子句.

The goal is to use it for user-defined n (2-100) without writing 100 if clauses.

if子句中的第二行减少了网格,因此column(n)<列(n + 1)

The second line in the if clauses reduces the grid so column(n) < column(n+1)

示例:

import numpy as np
dimension = 2
range = np.arange(0.2,2.4,0.1)
if dimension == 2:
    grid = np.array(np.meshgrid(range,range)).T.reshape(-1,dimension)
    grid = np.array(grid[[i for i in range(grid.shape[0]) if grid[i,0]<grid[i,1]]])
 elif dimension == 3:
     grid = np.array(np.meshgrid(range,range,range)).T.reshape(-1,dimension)
     grid = np.array(grid[[i for i in range(grid.shape[0]) if grid[i,0]<grid[i,1]]])
     grid = np.array(grid[[i for i in range(grid.shape[0]) if grid[i,1]<grid[i,2]]])

解决方案发布在下面:

dimension = 2
r = np.arange(0.2,2.4,0.1)
grid=np.array(np.meshgrid(*[r]*n)).T.reshape(-1,n)

for i in range(0,n-1):
    grid = np.array([g for g in grid if g[i]<g[i+1]])

推荐答案

我还没有完全吸收您的方法和目标,但这只是部分简化了

I haven't fully absorbed your approach and goals, but here's a partial simplification

In [399]: r=np.arange(3)           # simpler range for example
In [400]: grid=np.meshgrid(*[r]*2)   # use `[r]*3` for 3d case
In [401]: grid=np.array(grid).T.reshape(-1,2)
In [402]: np.array([g for g in grid if g[0]<g[1]])  # simpler comprehensions
Out[402]: 
array([[0, 1],
       [0, 2],
       [1, 2]])

itertools.product使两列网格更容易:

In [403]: from itertools import product
In [404]: np.array([g for g in product(r,r) if g[0]<g[1]])
Out[404]: 
array([[0, 1],
       [0, 2],
       [1, 2]])

也就是说,您的grid过滤前是

That is, your grid before filtering is

In [407]: grid
Out[407]: 
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2],
       [2, 0],
       [2, 1],
       [2, 2]])

product

In [406]: list(product(r,r))
Out[406]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

product具有一个repeat参数,这使此操作变得更加容易:

product has a repeat parameter that makes this even easier:

In [411]: list(product(r,repeat=2))
Out[411]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

您仍然需要if子句为dim = 3应用两步过滤.我想可以反复写

You still need the if clause to apply the 2 step filtering for dim=3. I guess the could written iteratively

for i in range(0,dimension-1):
   grid = [g for g in grid if g[i]<g[i+1]]

这篇关于具有numpy的网格的可变维数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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