How to Find the Number of Rows and Columns of a Matrix?
We can find matrix dimension with three ways:
- Using shape Attribute
- Using Indexing
- Using numpy.reshape()
Way 1: Using .shape Attribute
Here we are finding the number of rows and columns of a given matrix using Numpy.shape.
Python
import numpy as np matrix = np.array([[ 9 , 9 , 9 ], [ 8 , 8 , 8 ]]) dimensions = matrix.shape rows, columns = dimensions print ( "Rows:" , rows) print ( "Columns:" , columns) |
Output:
Rows: 2
Columns: 3
Way 2: Using Indexing
Here we are finding the number of rows and columns of a given matrix using Indexing.
Python
import numpy as np matrix = np.array([[ 4 , 3 , 2 ], [ 8 , 7 , 6 ]]) rows = matrix.shape[ 0 ] columns = matrix.shape[ 1 ] print ( "Rows:" , rows) print ( "Columns:" , columns) |
Output:
Rows: 2
Columns: 3
Way 3: Using numpy.reshape()
Here we are using numpy.reshape() to find number of rows and columns of a matrix, numpy.reshape
in NumPy is used for changing the shape of an array without modifying the underlying data.
When using
np.arange(start, stop)
, remember that the stop element is not included in the generated array. So,np.arange(1, 10)
will create an array with values from 1 to 9 (inclusive).
Python
import numpy as np matrix = np.arange( 1 , 10 ).reshape(( 3 , 3 )) print (matrix) # Original matrix print (matrix.shape) # Number of rows and columns of the said matrix |
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
(3,3)
Find the number of rows and columns of a given matrix using NumPy
The shape
attribute of a NumPy array returns a tuple representing the dimensions of the array. For a two-dimensional array, the shape tuple contains two values: the number of rows and the number of columns.
In this article, let’s discuss methods used to find dimensions of the matrix.
Contact Us