我对Python非常陌生,我正在尝试习惯于执行Python的数组操作,而不是在数组中循环。下面是我正在执行的循环操作的示例,但我无法计算出不依赖循环的合适纯数组操作:
import numpy as np
def f(arg1, arg2):
# an arbitrary function
def myFunction(a1DNumpyArray):
A = a1DNumpyArray
# Create a square array with each dimension the size of the argument array.
B = np.zeros((A.size, A.size))
# Function f is a function of two elements of the 1D array. For each
# element, i, I want to perform the function on it and every element
# before it, and store the result in the square array, multiplied by
# the difference between the ith and (i-1)th element.
for i in range(A.size):
B[i,:i] = f(A[i], A[:i])*(A[i]-A[i-1])
# Sum through j and return full sums as 1D array.
return np.sum(B, axis=0)
简言之,我正在积分一个函数,它以同一数组的两个元素作为参数,返回一个积分结果数组。你知道吗
有没有一种更紧凑的方法来实现这一点,而不使用循环?你知道吗
使用任意的
f
函数,这个[i, :i]
业务通过传递循环而变得复杂。你知道吗大多数快速编译的
numpy
操作都是对整个数组或整行和/或整列执行的,并且有效地并行执行。固有顺序的循环(一个循环的值取决于前一个循环)不适合。每个循环中不同大小的列表或数组也是一个很好的指标,表明“矢量化”将很困难。你知道吗对于样本
A
和已知的f
(简单到arg1*arg2
),我将生成一个B
数组,并寻找将B
作为一个整体处理的模式。乍一看,你的B
似乎是一个较低的三角形。有一些函数可以帮助索引这些。但最终的结果可能会改变情况。你知道吗有时我用自下而上的方法来解决这些问题,首先尝试移除内部循环。但在这种情况下,我认为需要某种大局观的方法。你知道吗
相关问题 更多 >
编程相关推荐