2

In Python, I am trying to initialize 2-element arrays of zeros within a size N by N array. The code I'm using works but I'm looking for something more efficient and elegant:

array1 = np.empty((N,N), dtype=object)
for i in range(N):
    for j in range(N):
        array1[i,j] = np.zeros(2, dtype=np.int)

Thank ahead for the help

6
  • 1
    Is there any requirement why you each element should be array of 2.? Does dimension of (N,N,2) will work? Commented Oct 8, 2019 at 17:56
  • 2
    It as unclear what you are trying to do: to you really want an array of array (for N=2 with your code you get array1 = array([[array([0, 0]), array([0, 0])], [array([0, 0]), array([0, 0])]], dtype=object)), a 3D array (size NxNx2 for instance) or a big 2D array (size 2Nx2N)? Maybe there would be a better solution to your code problem than what you got with this sample... Tell us more! Commented Oct 8, 2019 at 19:31
  • @Poojan, no requirement. Any array size will suffice. Commented Oct 10, 2019 at 9:10
  • @jeannej, yes a 3D array could work. But, I will need to initialize the first 2 dimensions as empty and then the third dimension as an array of zeros. Any ideas? Commented Oct 10, 2019 at 9:10
  • 3
    @nrcjea001 Is there any reason why this will not work? np.zeros(N,N,2) ? Commented Oct 10, 2019 at 16:29

1 Answer 1

3

As I understand it, you should probably use a 3D array:

import numpy as np
array1 = np.empty((N,N,2), dtype=object)

which returns an array of N rows, N columns and 2 depth. If you want to pass a (NxN) array to let's say the first depth, just use:

tmp = np.ones(N,N) #for instance
array1(:,:,0) = tmp
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.