How to find the length (or dimensions, size) of a numpy matrix in python?

For numpy matrix in python

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

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

So far, the only solution I have found is:

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

which returns 2, 2, and 1, respectively. From this, I gathered that len() will return the number of rows, so I can always transpose, len(AT) , for the number of columns. However, this seems unsatisfactory and arbitrary, since when reading a line, len(A) does not immediately become obvious that this should return the number of lines. It really works differently than len([1,2]) for a python 2D array, as this will return 2.

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

+75
python numpy matrix
Feb 13 '13 at 6:07
source share
2 answers

shape is a property of both numpy ndarray 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 created on top of the ndarray object, one of the two main objects (along with the universal functional object), so it inherits from ndarray

+150
Feb 13 '13 at 6:07
source share

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

+18
Feb 13 '13 at 6:12
source share



All Articles