【发布时间】:2014-10-06 06:28:49
【问题描述】:
我想初始化一个 numpy 数组以表示 100 x 100 点网格上的二维向量场,该点由以下定义:
import numpy as np
dx = dy = 0.1
nx = ny = 100
x, y = np.meshgrid(np.arange(0,nx*dx,dx), np.arange(0,ny*dy,dy))
该字段是关于点 cx,cy 的恒速循环,我可以使用常规 Python 循环对其进行初始化:
v = np.empty((nx, ny, 2))
cx, cy = 5, 5
s = 2
for i in range(nx):
for j in range(ny):
rx, ry = i*dx - cx, j*dy - cy
r = np.hypot(rx, ry)
if r == 0:
v[i,j] = 0,0
continue
# (-ry/r, rx/r): the unit vector tangent to the circle centred at (cx,cy), radius r
v[i,j] = (s * -ry/r, s * rx/r)
但是当我无法使用 numpy 进行矢量化时。我得到的最接近的是
v = np.array([s * -(y-cy) / np.hypot(x-cx, y-cy), s * (x-cx) / np.hypot(x-cx, y-cy)])
v = np.rollaxis(v, 1, 0)
v = np.rollaxis(v, 2, 1)
v[np.isinf(v)] = 0
但这并不等同,也没有给出正确的答案。使用 numpy 初始化向量场的正确方法是什么?
编辑:好的 - 现在我对以下建议感到困惑,我尝试:
vx = s * -(y-cy) / np.hypot(x-cx, y-cy)
vy = s * (x-cx) / np.hypot(x-cx, y-cy)
v = np.dstack((vx, vy))
v[np.isnan(v)] = 0
但是得到一个完全不同的数组...
【问题讨论】:
-
我不确定我是否关注你——如果我正在矢量化,我没有明确的索引 i 和 j。
-
我认为您的示例中有一个错字:
cx = cy= 5, 5将元组(5, 5)分配给cx和cy。你的意思可能是cx, cy = 5, 5。 -
感谢您的收获!我现在已经在我的帖子中修复了它,因为它不是我的问题的原因。
标签: python arrays numpy vector vectorization