Skip to content
Advertisement

How to efficiently create multidimensional arrays?

assuming I have any function such as

f(x, y, z) = xyz

what’s the fastest way of calculating every value for f given three linear input arrays x, y, and z?

Of course I can do something along the lines of,

import numpy as np

x = np.linspace(-1., 1., 11)
y = np.linspace(-1., 1., 11)
z = np.linspace(-1., 1., 11)

for xi, xx in enumerate(x):
    for yi, yy in enumerate(y):
        for zi, zz in enumerate(z):
            f(xi, yi, zz) = xx*yy*zz

but this is probably not the best way to do it, especially if the input arrays become larger. Is there a better way of doing it, such as with a list comprehension (but multidimensional) or any other way? Help is appreciated.

Advertisement

Answer

First create the grid mesh array (x,y,z) as 3-tuples using meshgrid then you can apply the function in sequence:

import numpy as np
x = y = z = np.linspace(-1.0,1.0,11)
grid_coordinates = np.array(np.meshgrid(x,y,z)).reshape(-1,3)
f = lambda x,y,z : x*y*z
f_values = [ f(x,y,z) for x,y,z in grid_coordinates ]

A unit test for the f_values,

f_values[10] == grid_coordinates[10][0]*grid_coordinates[10][1]*grid_coordinates[10][2]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement