Matrices in numpy

To work with matrices, numpy provides a special object called matrix. In numpy, a matrix is a specialized 2D array that retains its 2D nature through operations.

We can create numpy matrices using the following syntax:

matrix-name = matrix(2D array or string)

It means, the matrix object receives a 2D array or a string that contains elements which can be converted into a matrix.

For example, we are taking a 2D array with 2 rows and 3 columns as:

arr = [[1, 2, 3], [4, 5, 6]]

This array can be converted into a matrix ‘a’ as:

a = matrix(arr)

Alternately, we can also pass the 2D array directly to matrix object as:

a = matrix([[1,2,3],[4,5,6]])

Another way of creating a matrix is by passing a string with elements to matrix object as:

str = ‘1 2; 3 4; 5 6’

b = matrix(str)

numpy diagonal function matrix

To retrieve the diagonal elements of a matrix, we can use diagonal() function as:

a = diagonal(matrix)

The diagonal() function returns a 1D array that contains diagonal elements of the original matrix.

To understand this function, we can take an example.

a = matrix('1 2 3; 4 5 6; 7 8 9')

The preceding lines of code will display the following output:
[[1 2 3]
[4 5 6]
[7 8 9]]
Consider the following code:

d = diagonal(a)

Finding Maximum and Minimum Elements

To know the maximum element, we can use max() method and to know the minimum element, we can use min() methods. These methods should be called using the matrix name.

big = a.max()



small = a.min()



Finding Sum and Average of Elements

To find sum of all the elements in the matrix, we can use sum() method and to find average, we can use mean() method. These methods should be called using the matrix name.





Sorting the Matrix

numpy provides sort() function that sorts the matrix elements into ascending order.

sort(matrixname, axis)

Python numpy transpose matrix

Rewriting matrix rows into columns and vice versa is called ‘transpose’. To find the transpose, we can use transpose() and getT() methods in numpy. These methods should be called using matrix name.

m = matrix('1 2 3; 4 5 6; 7 8 9')


[[1 2 3]

[4 5 6]

[7 8 9]]

t = m.transpose()


[[1 4 7]

[2 5 8]

[3 6 9]]



[[1 4 7]

[2 5 8]

[3 6 9]]

A Python program to accept a matrix from the keyboard and display its transpose matrix.

Matrix Addition

We can use arithmetic operators like +, - and/ to perform addition, subtraction and division operations on 2 matrices. Consider the following code snippet:

Matrix Multiplication

A Python program to accept two matrices and find their product.