[英]numpy iterate over two 2d arrays
Say I have two matrices: 假设我有两个矩阵:
X, Y = np.meshgrid(np.arange(0, 2, 0.1), np.arange(3, 5, 0.1))
And a function, something like: 还有一个函数,例如:
def func(x) :
return x[0]**2 + x[1]**2
How can I fill a matrix Z
(of size np.shape(X)), where each entry is formed by calling func
on the two corresponding values of X
and Y
, ie: 如何填充矩阵
Z
(大小为np.shape(X)),其中每个条目都是通过对X
和Y
的两个对应值调用func
来形成的,即:
Z[i, j] = func([X[i, j], Y[i, j]])
Is there a way without using a double nested for-loop? 有没有不使用双嵌套for循环的方法?
For given numpy arrays X
and Y
, you could just do - 对于给定的numpy数组
X
和Y
,您可以执行以下操作-
Zout = X**2 + Y**2
If you are actually constructing X
and Y
like that, there is a direct way to get Z
with broadcasting
and thus avoid np.meshgrid
, like so - 如果您实际上是这样构造
X
和Y
,那么有一种直接方法可以通过broadcasting
获取Z
,从而避免使用np.meshgrid
,就像这样-
Zout = np.arange(0, 2, 0.1)**2 + np.arange(3, 5, 0.1)[:,None]**2
This is also works as a vectorized form of function evaluation: 这也可以作为函数评估的向量化形式:
import numpy as np
X, Y = np.meshgrid(np.arange(0, 2, 0.1), np.arange(3, 5, 0.1))
def func(x) :
return x[0]**2 + x[1]**2
Z = func([X,Y])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.