Question

I have a numpy array D of dimensions 4x4

I want a new numpy array based on an user defined value v

If v=2, the new numpy array should be [D D]. If v=3, the new numpy array should be [D D D]

How do i initialise such a numpy array as numpy.zeros(v) dont allow me to place arrays as elements?

Was it helpful?

Solution

If I understand correctly, you want to take a 2D array and tile it v times in the first dimension? You can use np.repeat:

# a 2D array
D = np.arange(4).reshape(2, 2)

print D
# [[0 1]
#  [2 3]]

# tile it 3 times in the first dimension
x = np.repeat(D[None, :], 3, axis=0)

print x.shape
# (3, 2, 2)

print x
# [[[0 1]
#   [2 3]]

#  [[0 1]
#   [2 3]]

#  [[0 1]
#   [2 3]]]

If you wanted the output to be kept two-dimensional, i.e. (6, 2), you could omit the [None, :] indexing (see this page for more info on numpy's broadcasting rules).

print np.repeat(D, 3, axis=0)
# [[0 1]
#  [0 1]
#  [0 1]
#  [2 3]
#  [2 3]
#  [2 3]]

Another alternative is np.tile, which behaves slightly differently in that it will always tile over the last dimension:

print np.tile(D, 3)
# [[0, 1, 0, 1, 0, 1],
#  [2, 3, 2, 3, 2, 3]])

OTHER TIPS

You can do that as follows:

import numpy as np
v = 3
x = np.array([np.zeros((4,4)) for _ in range(v)])

>>> print x
[[[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]]

Here you go, see if this works for you.

import numpy as np
v = raw_input('Enter: ')

To intialize the numpy array of arrays from user input (obviously can be whatever shape you're wanting here):

b = np.zeros(shape=(int(v),int(v)))

I know this isn't initializing a numpy array but since you mentioned wanting an array of [D D] if v was 2 for example, just thought I'd throw this in as another option as well.

new_array = []
for x in range(0, int(v)):
    new_array.append(D)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top