I have 3 one-dimensional numpy arrays x , y and z.
I want to use the values of these numpy arrays to create a 3D numpy array (say result) whose values are functions of values contained in x , y and z. I want the shape of result to be ( len(x) , len(y) , len(z) ). Value contained in each index of result is obtained from a non-linear function (say func ) which uses corresponding elements from x , y and z. As an example, the value contained in result[i,j,k] is obtained from func(x[i] , y[j] , z[k]). The same linear function is used to obtain all elements of result. What is the most efficient way of doing this? In my actual work, the arrays x, y and z will be of very big sizes.
I am giving an example of the code that I am using below. This code uses the function func = sin(x2) • sin(y2) • sin(z2) This function is just one example of a non-linear function. I will like the code to not be specific to the aforementioned function (i.e., I will like the code to have the provision to use other different non linear functions.) Following is the code that I have now:
import numpy as np
x = np.array([1,2,3])
y = np.array([4,5,6])
z = np.array([7,8,9])
def func( xval, yval, zval ):
return np.sin(xval**2) + np.sin( yval**2 ) + np.sin( zval**2 )
results = np.zeros( shape=( len(x) , len(y) , len(z) ) )
for i in range(len(x)):
for j in range(len(y)):
for k in range(len(z)):
results[i,j,k] = func( x[i], y[j], z[k] )
Any help will be appreciated.
func. If it only works with scalar values, then it has to be called once for each combination ofx,y,z. The iteration method doesn't make much difference. But if it accepts whole arrays, and better yet makes use ofnumpybroadcasting, it can be called just once, with the wholex,y,zgrid - that will be fast. Thefuncas written should work this way.