OKPEDIA PYTHON MATRIX

How to find the number of rows and columns of a matrix in python

To find out the number of rows and columns of a matrix in Python use the function shape of NumPy.

shape(m)

The m parameter is an array

The shape function outputs the number of rows and columns of the matrix.

Note. The shape function of NumPy can also be called as a method of a vector object. For example, m.shape.

Examples

Example 1

Import the Python NumPy library

>>> import numpy as np

Create an array using the array() function.

>>> M=np.array([[1,2,3],[4,5,6]])

It is a 2x3 rectangular matrix.

a matrix example

Type the shape() function and indicate the name of the matrix in brackets.

>>> shape(M)

The shape function returns the number of rows and columns in the array.

(2, 3)

The matrix has two rows and three columns.

Note. The result is a tuple with integer values separated by a comma. The first element is the number of rows in the matrix, the second element is the number of columns.

Example 2

The previous exercise can also be solved using the method shape.

>>> M.shape

The result is the same.

(2, 3)

https://how.okpedia.org/en/python/how-to-find-the-number-of-rows-and-columns-of-a-matrix-in-python


Report us an error or send a suggestion to improve this page


Matrix in Python


FacebookTwitterLinkedinLinkedin