1

I have a matrix "a" that has the following properties:

a.shape

(3, 220)

a.shape[1]

220

len(a)

3

len(a[0])

1

a[0].shape

(1, 220)

I don't get why len(a[0]) is different from a.shape[1]. It seems like I can never access the subarray a[0]. Please help me to understand why that is the case. Thanks!

Flamy
  • 11
  • 1
  • 2
    That's because you're using `numpy.matrix`. This is one of the reasons you shouldn't use `numpy.matrix`. Stop using `numpy.matrix`. – user2357112 Nov 10 '19 at 04:11

2 Answers2

2

Note, numpy recommends here that np.matrix should not be used, instead just use arrays:

It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.

If you check out what a[0] is, you'll see the problem. Let's implement this in a smaller size so that it's easier to visualize:

import numpy as np

# I'm using all zeros here for simplicity
y = np.matrix(np.zeros((5, 10)))

y.shape
(5, 10)

y[0]
matrix([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

y[0] is a matrix consisting of 1 row and 10 columns:

y[0].shape
(1, 10)

If you use np.array, you avoid this problem altogether

x = np.zeros((5, 10))

x.shape
(5, 10)

len(x[0])
10

x[0].shape
(10,)

C.Nivs
  • 12,353
  • 2
  • 19
  • 44
0

As user2357112 pointed out, the problem appears to be that you are using numpy.matrix instead of numpy.ndarray (via numpy.array).

The Numpy documentation says the following about matrix:

It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.

A regular Numpy array is very similar to a matrix, but can have any number of dimensions, and use the @ operator instead of * to do matrix multipliation.

jirassimok
  • 3,850
  • 2
  • 14
  • 23