Python, Numpy
Is there a more compact way to operate on array elements, without having to use the standard for loop.?
For example, consider the function below:
filterData(A):
B = numpy.zeros(len(A));
B[0] = (A[0] + A[1])/2.0;
for i in range(1, len(A)):
B[i] = (A[i]-A[i-1])/2.0;
return B;
Numpy has a diff operator that works on both numpy arrays and Python native arrays. You can rewrite your code as:
def filterData(A):
B = numpy.zeros(len(A));
B[1:] = np.diff( A )/2.0
B[0] = (A[0] + A[1])/2.0;
return B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With