Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

2 Answers

0 votes
by (106k points)

To find the length of a numpy matrix in Python you can use shape which is a property of both numpy ndarray's and matrices.

A.shape

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

If you are interested to learn Python from Industry experts, you can sign up for this Python Certification Course by Intellipaat.

0 votes
by (1.9k points)

To find the number of rows and columns in a matrix using NumPy, one can use the.shape attribute, which is intuitively more meaningful than a call to len(). If you have defined a matrix like this:

from numpy import matrix

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

You can literally just write num_rows, num_columns = A. shape. This will both print out the number of rows and the number of columns directly. Here it would print out (2, 2) because you have 2 rows, 2 columns in your matrix.

 Using.shape is more direct and easier on the eyes than using len() because it gives you the dimensions of your matrix directly without extra work. It makes your matrix size at a glance easier to read.

Related questions

0 votes
1 answer
asked Jul 17, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Mar 21, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 24, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...