[SciPy-User] Creating meshgrid from meshgrid
Pauli Virtanen
pav at iki.fi
Wed Sep 6 04:05:54 EDT 2017
Florian Lindner kirjoitti 06.09.2017 klo 06:31:
[clip]
> def fun(x):
> return x
>
> mgrid = np.meshgrid( a,b )
> A = fun( np.abs(mgrid[0] - mgrid[1] ) )
>
> Result A is of size N x N:
>
> array([[ 9, 8, 7],
> [19, 18, 17],
> [29, 28, 27]])
Don't use meshgrid, use broadcasting:
from numpy import newaxis
ax = np.array([0, 1, 2])
ay = np.array([4, 5])
bx = np.array([7, 8, 9, 10])
by = np.array([11, 12, 13, 14])
def fun(x1, y1, x2, y2):
return abs(x1 - x2) + abs(y1 - y2)
d = fun(ax[:,newaxis,newaxis,newaxis],
ay[newaxis,:,newaxis,newaxis],
bx[newaxis,newaxis,:,newaxis],
by[newaxis,newaxis,newaxis,:])
or
p1 = np.array([[0,1], [1,3], [5,6], [7,9]])
p2 = np.array([[3,6], [2,7], [9,2], [1,3]])
def fun(a, b):
return np.hypot(a[...,0] - b[...,0], a[...,1] - b[...,1])
d = fun(p1[:,newaxis,:], p2[newaxis,:,:])
depending on what it is that you actually want to evaluate.
--
Pauli Virtanen
More information about the SciPy-User
mailing list