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

Python

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 use 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?


If you want to unleash your potential in this competitive field, please visit the Python course page for more information, where you can find the Python tutorials and Python frequently asked interview questions and answers as well.

1
Answers

Replies


You can use the shape property to get the matrix size. It will return a tuple with the number of rows and columns. Here is how you can use it.



from numpy import matrix


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


print(A.shape)



(2, 2)


 

 
 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
WhatsApp
To Top