I am creating a 2d numpy array from a function applied to a 1d numpy array (which contains a conditional) and would like to know a more efficient way of doing this. This is currently the slowest part of my code. x is a 1d numpy array, and the output is a 2d numpy array. There is a switch to construct a different array element based on whether x is less than or greater than 0. In the future, there could be an arbitrary number of switches.
def basis2(x) :
final = []
for i in x :
if i > 0 :
xr = 2.0*(i-0.5)
final.append(np.array([0.0, 0.0, 0.0, 0.5*xr*(xr-1.0),-1.0*(xr+1)*(xr-1), 0.5*xr*(xr+1.0)]))
else :
xl = 2.0*(i+0.5)
final.append(np.array([0.5*xl*(xl-1.0),-1.0*(xl+1)*(xl-1),0.5*xl*(xl+1.0),0.0,0.0,0.0]))
return np.array(final)
Ideally, I would be able to eliminate the for loop - but so far I have not managed to do this properly, using 'where' for example. Thanks, for any help.
xinto two arrays, on wherex<=0and the otherx>0? And then evaluate each expression with a whole array? What's the essential difference between the two expressions? Give a sample ofx.