I have these two arrays:
import numpy as np
a = np.array([0, 10, 20])
b = np.array([20, 30, 40, 50])
I'd like to add both in the following way:
for i in range (len(a)):
for j in range(len(b)):
c = a[i] + b[j]
d = delta(c, dr)
As you see for each iteration I get a value c which I pass through a function delta (see note at the end of the post).
The thing is that I want to avoid slow Python "for" loops when the arrays are huge.
One thing I could do would be:
c = np.ravel(a(-1, 1) + b)
Which is much much faster. The problem is that now c is an array, and again I would have to go throw it using a for loop.
So, do you have any idea on how I could do this without using a for loop at all.
NOTE: delta is a function I define in the following way:
def delta(r,dr):
if r >= 0.5*dr and r <= 1.5*dr:
delta = (5-3*abs(r)/dr-np.sqrt(-3*(1-abs(r)/dr)**2+1))/(6*dr)
elif r <= 0.5*dr:
delta = (1+np.sqrt(-3*(r/dr)**2+1))/(3*dr)
else:
delta = 0
return delta
functiona suitable NumPyufunc, or a Python function? In the former case, you might be able to optimize; in the latter, you wouldn't.deltafunction takes two variables, not one as in theforloop. Also, it doesn't return anything. Did you intend to return thedeltavariable?