4

Given a closed-form function f(x,y,z), what is the most efficient way to fill up a 3D ndarray arr[z][y][x] with the values of f(x,y,z)?

For example, if I wanted a 3D ndarray arr[z][y][x] with each element taking the value max((x+1)/(y+1), (y+1)/(z+1)), is there any better way to do so than iterating over the array element by element?

3
  • 1
    We normally write indexing as arr[x,y,z]. Ideally the indices will be arrays or slices. What kinds of values can your function take? Just scalars, or arrays? In other words can you only set individual elements at a time, or can you set blocks or ranges? Commented Oct 11 at 21:45
  • Your example works with array inputs. There are a number ways of generating the required arrays. Commented Oct 11 at 23:40
  • Look at the suggested ogrid arrays. Maybe even try to creat them from scratch. It'll be a good learning step. Commented Oct 12 at 0:43

1 Answer 1

5

You can do this with ogrid:

# Shape of the desired array
m, n, p = 3, 4, 5

# Indexers in each dimension
x, y, z = np.ogrid[:m, :n, :p]

# Broadcasting in action with your function
print(np.maximum((x+1)/(y+1), (y+1)/(z+1)))

yields

[[[1.         1.         1.         1.         1.        ]
  [2.         1.         0.66666667 0.5        0.5       ]
  [3.         1.5        1.         0.75       0.6       ]
  [4.         2.         1.33333333 1.         0.8       ]]

 [[2.         2.         2.         2.         2.        ]
  [2.         1.         1.         1.         1.        ]
  [3.         1.5        1.         0.75       0.66666667]
  [4.         2.         1.33333333 1.         0.8       ]]

 [[3.         3.         3.         3.         3.        ]
  [2.         1.5        1.5        1.5        1.5       ]
  [3.         1.5        1.         1.         1.        ]
  [4.         2.         1.33333333 1.         0.8       ]]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.