164

For a numpy matrix in python

from numpy import matrix
A = matrix([[1,2],[3,4]])

How can I find the length of a row (or column) of this matrix? Equivalently, how can I know the number of rows or columns?

So far, the only solution I've found is:

len(A)
len(A[:,1])
len(A[1,:])

Which returns 2, 2, and 1, respectively. From this I've gathered that len() will return the number of rows, so I can always us the transpose, len(A.T), for the number of columns. However, this feels unsatisfying and arbitrary, as when reading the line len(A), it isn't immediately obvious that this should return the number of rows. It actually works differently than len([1,2]) would for a 2D python array, as this would return 2.

So, is there a more intuitive way to find the size of a matrix, or is this the best I have?

Kyle Heuton
  • 9,318
  • 4
  • 40
  • 52
  • First result for numpy dimensions btw, try the search box ... – wim Feb 13 '13 at 06:23
  • 1
    Thanks for pointing me to that question! I did try searching, but "numpy matrix dimensions" (or length or size for that matter) didn't result in anything useful. I read numpy tutorials, but shape was covered in the ndarray section, and I didn't make the connection that properties of ndarray's would be extended to matrices. I attempted to solve my problem by switching to numpy arrays, but these didn't have the linear algebra properties of matrices, furthering my belief that they didn't share properties – Kyle Heuton Feb 13 '13 at 06:28

2 Answers2

280

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Kyle Heuton
  • 9,318
  • 4
  • 40
  • 52
41

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

hd1
  • 33,938
  • 5
  • 80
  • 91