MisterTea
MisterTea

Reputation: 31

creating a 2D array of path coordinates from 1d arrays

I am trying to generate an array of coordinates from 1d-lists of X Y Z positions. The software I use iterates along each list which are nested by a given order of priority. In other words, if I have x = [x0, x1], y = [y0, y1] and z = [z0, z1] and if the priority is z>y>x the corresponding array would be:

x0 y0 z0
x0 y0 z1
x0 y1 z0
x0 y1 z1
x1 y0 z0
x1 y0 z1
x1 y1 z0
x1 y1 z1

I have tried using list comprehensions, however the input is 1d ndarrays and not lists, which requires me to convert the data to lists, then the result back to an ndarray (list comprehensions may also lack flexibility in some cases I am trying to implement). Are there functions in numpy that could help to generate such an array?

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
out = [[i, j, k] for i in x for j in y for k in z]
out = np.asarray(out)

output

[[1, 4, 7],
 [1, 4, 8],
 [1, 4, 9],
 [1, 5, 7],
 [1, 5, 8],
 [1, 5, 9],
 [1, 6, 7],
 [1, 6, 8],
 [1, 6, 9],
 [2, 4, 7],
 [2, 4, 8],
 [2, 4, 9],
 [2, 5, 7],
 [2, 5, 8],
 [2, 5, 9],
 [2, 6, 7],
 [2, 6, 8],
 [2, 6, 9],
 [3, 4, 7],
 [3, 4, 8],
 [3, 4, 9],
 [3, 5, 7],
 [3, 5, 8],
 [3, 5, 9],
 [3, 6, 7],
 [3, 6, 8],
 [3, 6, 9]]

Upvotes: 0

Views: 677

Answers (2)

Shehan Ishanka
Shehan Ishanka

Reputation: 593

Try this.

np.array(np.meshgrid(x,y,z)).T.reshape(-1,3)

OUTPUT:

[[1 4 7]
 [1 5 7]
 [1 6 7]
 [2 4 7]
 [2 5 7]
 [2 6 7]
 [3 4 7]
 [3 5 7]
 [3 6 7]
 [1 4 8]
 [1 5 8]
 [1 6 8]
 [2 4 8]
 [2 5 8]
 [2 6 8]
 [3 4 8]
 [3 5 8]
 [3 6 8]
 [1 4 9]
 [1 5 9]
 [1 6 9]
 [2 4 9]
 [2 5 9]
 [2 6 9]
 [3 4 9]
 [3 5 9]
 [3 6 9]]

Upvotes: 1

M. Zidan
M. Zidan

Reputation: 156

Yes, you could use np.repeat and np.tile

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

out = np.zeros((len(x)**3, 3))
out[:, 0] = np.repeat(x, len(x)**2)
out[:, 1] = np.tile(np.repeat(y, len(x)), 3)
out[:, 2] = np.tile(z, len(x)**2)

output:

[[1. 4. 7.]
 [1. 4. 8.]
 [1. 4. 9.]
 [1. 5. 7.]
 [1. 5. 8.]
 [1. 5. 9.]
 [1. 6. 7.]
 [1. 6. 8.]
 [1. 6. 9.]
 [2. 4. 7.]
 [2. 4. 8.]
 [2. 4. 9.]
 [2. 5. 7.]
 [2. 5. 8.]
 [2. 5. 9.]
 [2. 6. 7.]
 [2. 6. 8.]
 [2. 6. 9.]
 [3. 4. 7.]
 [3. 4. 8.]
 [3. 4. 9.]
 [3. 5. 7.]
 [3. 5. 8.]
 [3. 5. 9.]
 [3. 6. 7.]
 [3. 6. 8.]
 [3. 6. 9.]]

If you know a priori that the coordinates are integers, you could even:

out = np.zeros((len(x)**3, 3), dtype=int)

Upvotes: 0

Related Questions