Construct identity matrix

An identity matrix is a square matrix, having equal number of rows and columns, and with diagonal elements equal to one and all other elements other than diagonal equal to zero. It is often denoted as “I” or “eye”. The identity matrix is significant due to its usefulness in matrix algebra and linear algebra operations. It serves as a multiplicative identity and transformation matrix to maintain original data. It also involved in computing eigenvalues and eigenvectors. In this thread, we will learn how to construct an identity matrix using NumPy. We will create, 3x3 identity matrix as show below:

 [[1 0  0],[0 1 0], [0 0 1]] 

1. Using "identity()" function:

The NumPy, "identity()" function returns a square array (i.e., the number of rows is equal to the number of columns) with ones on the diagonal and zeros elsewhere.
  • identity() function takes one required argument n(shape) , which specifies the number of rows (and columns) of the resulting identity matrix.

For example, numpy.identity(3) creates a 3x3 identity array below:

2. By "zeros()" and "fill_diagonal()" function:

  • In NumPy, the zeros() function creates an array filled with zeros. It takes one mandatory argument, shape , which is a tuple specifying the shape of the array.

  • fill_diagonal() function fills the diagonal of an array with a specified value. It takes two required arguments: the input array and the value to be assigned to the diagonal elements.

For example, the following code creates a 3x3 array of zeros((3, 3)) and fills the diagonal of a 3x3 array with the value 1, which helps in construct identity matrix.

3. Using "reshape() function:

  • In NumPy, array() function is a fundamental method that is used to create a new NumPy array object. It required one argument n , which can be a list, tuple, or other iterable containing the values to be stored in the array.

  • The reshape() function is used to change the shape of an existing array without changing its values. The function takes two required argument n , one is the input array, and other is the new shape of the array s.

For example, the following code creates a 1-dimensional array with identity values and reshape it in 3x3 matrix.