0

How do I make a matrix that consists of elements that are lists? For example

t = np.zeros(((N+1),(N+1)))
for row in range (N+1):
    for column in range (N+1):
        position = [row,column]
        t[row,column] = position

But this gives an error saying "setting an array element with a sequence."

I want the code to create something like

[[[0,0],[0,1],[0,2]],
 [[1,0],[1,1],[1,2]],
 [[2,0],[2,1],[2,2]]]
Brittany
  • 5
  • 4

2 Answers2

1

Your data is 3-dimensional, so your array is missing its last dimension:

t = np.zeros(((N+1),(N+1),2))
# for loops...

And why not use numpy.indices()? This task is what it's for:

t = numpy.indices((N+1, N+1))[::-1, :].T
# array([[[0, 0],
#         [0, 1],
#         [0, 2]],
# 
#        [[1, 0],
#         [1, 1],
#         [1, 2]],
# 
#        [[2, 0],
#         [2, 1],
#         [2, 2]]])

The advantage of using 3D data should be immediately clear, as you can easily index the list dimension, too. E.g. to print only the second value of all lists

t[..., 0]
# array([[0, 0, 0],
#        [1, 1, 1],
#        [2, 2, 2]])

or plotting your data:

plt.figure()
plt.imshow(t[..., 0])  # plot first value of lists
plt.figure()
plt.imshow(t[..., 1])  # plot second value of lists
plt.show()

or any other method of processing your data:

numpy.sum(t, axis=1)
# array([[0, 3],
#        [3, 3],
#        [6, 3]])

or

t / numpy.max(t)
# array([[[ 0. ,  0. ],
#         [ 0. ,  0.5],
#         [ 0. ,  1. ]],
# 
#        [[ 0.5,  0. ],
#         [ 0.5,  0.5],
#         [ 0.5,  1. ]],
# 
#        [[ 1. ,  0. ],
#         [ 1. ,  0.5],
#         [ 1. ,  1. ]]])

those are things you obviously cannot do if your array is a 2D array of lists.

Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • I'm pretty new to python so I don't know too much about numpy. Is there a way that I can use 'numpy.indices()' and have the output look like what I have above instead of the format where it looks like three matrices? – Brittany May 17 '17 at 18:44
  • Its just NumPys way or representing 3 dimensions. If you disregard newlines (they're presentation, not data), they're identical. – Nils Werner May 17 '17 at 20:07
  • The problem with the presentation is that I will most likely have a large N therefore viewing the matrix that with all the newlines isn't desirable. – Brittany May 17 '17 at 23:00
  • I would argue that for large N you will see a huge amount of numbers and will be unable to make out patterns anyways. In that case I would suggest using matplotlib to visualize data. And again, you can only do that if you have the right `dtype`, that isn't `object`. – Nils Werner May 18 '17 at 07:38
0

You need to have the dtype of the elements in ndarray as object:

a = np.zeros([N+1, N+1], dtype=object)
a[0][0] = [1, 2, 3]
peidaqi
  • 673
  • 1
  • 7
  • 18