I am looking at how to speed up one of my functions. The function is called with a number of two-dimensional arrays of the same size. I want to combine these into a 4D with 3x3 in the last two dimensions, and later get the eigenvalues of the whole array.
I have managed to do it using two nested for loops, but it is a bit slower then I would desire, so is there any good way of speeding up the code?
def principal(xx, xy, xz, yy, yz, zz):
import numpy as np
xx = np.array(xx)
xy = np.array(xy)
xz = np.array(xz)
yy = np.array(yy)
yz = np.array(yz)
zz = np.array(zz)
size = np.shape(xx)
Princ = np.empty((size[1], size[0], 3, 3))
for j in range(size[1]):
for i in range(size[0]):
Princ[j, i, :, :] = np.array([[xx[i, j], xy[i, j], xz[i, j]],
[xy[i, j], yy[i, j], yz[i, j]],
[xz[i, j], yz[i, j], zz[i, j]]])
Princ = np.linalg.eigvalsh(Princ)
return Princ
import numpy as np
number_arrays_1 = 3
number_arrays_2 = 4
xx = np.ones((number_arrays_1, number_arrays_2))*80
xy = np.ones((number_arrays_1, number_arrays_2))*30
xz = np.ones((number_arrays_1, number_arrays_2))*0
yy = np.ones((number_arrays_1, number_arrays_2))*40
yz = np.ones((number_arrays_1, number_arrays_2))*0
zz = np.ones((number_arrays_1, number_arrays_2))*60
Princ = principal(xx, xy, xz, yy, yz, zz)
print(Princ)
The reason I convert with xx = np.array(xx) is that in the larger program, I pass a pandas dataframe rather than a numpy array into the function.
xxetc always benp.ones(....)*c? Or is that just convenience for this example?