[英]How to create matrix of tuple coordinates using numpy and then apply a function to each element?
我不确定是否可以在numpy
执行此操作,但是我想创建一个坐标元组。
例如,对于3x3矩阵,我希望矩阵为:
[[(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)]]
因为最终我想将坐标传递给函数并创建函数结果的矩阵
因此,如果调用该函数myfunc
类型为(i,j) -> k
我希望结果矩阵看起来像这样
[[myfunc(0,0), myfunc(0,1), myfunc(0,2)],
[myfunc(1,0), myfunc(1,1), myfunc(1,2)],
[myfunc(2,0), myfunc(2,1), myfunc(2,2)]]
我看过像np.meshgrid
这样的解决方案:
i_indices, j_indices = np.meshgrid(np.arange(3),np.arange(3),indexing='ij')
但是后来我仍然陷入困境,我不知道如何在没有for循环的情况下迭代那些坐标矩阵i_index
和j_index
来创建所需的结果矩阵。
基本上可以在numpy中做到吗? 如果是这样,怎么办? 还是必须使用for循环?
我意识到我只需要使用np.vectorize
i_indices, j_index = np.meshgrid(np.arange(3),np.arange(3),indexing='ij')
myfunc = // some lambda function
v_myfunc = np.vectorize(myfunc)
result_matrix = v_myfunc(i_index, j_indices)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.