Create Matrix in NumPy | Identity Matrix and Diagonal Matrix using numpy.eye() & numpy.diag() Functions

A NumPy matrix is a 2-D array, a rectangular grid of numbers organized in rows and columns. In NumPy, the matrix class is a specialized 2-D ndarray object, and it enforces a stricter 2-D structure, meaning it only supports two-dimensional arrays. NumPy library provides additional methods specifically designed for matrix operations.

In previous articles, we learned about NumPy Arrays and How to create NumPy Arrays using Lists or Tuples or using different methods like np.arange(), np.linspace() and np.logspace(). In this article, we will learn about how to create NumPy Matrix, ways to create Identity Matrix and Diagonal Matrix.

How to Create Matrix in NumPy

To create a NumPy matrix, we use the numpy.matrix function or simply work with a NumPy array (as an array can be treated like a matrix in many cases). Majorly, there are two ways to create a matrix in NumPy.

Create Matrix in NumPy using numpy.matrix() from a List

This method creates a matrix object. It’s less commonly used today, as numpy.ndarray is preferred, but it’s still part of NumPy.

import numpy as np

matrix= np.matrix([[16, 26], [38, 42]]) # Create a 2x2 matrix
print(matrix)
# Output => [[16 26][38 42]]

This creates a 2×2 matrix with the values provided in the list.

Create Matrix in NumPy using numpy.array()

Most of the time, you would use numpy.array() to create a 2-D array that can act as a matrix. The key difference between an ndarray and a matrix is that an ndarray can be of any number of dimensions, while a matrix is strictly 2D.

import numpy as np

array = np.array([[16, 26], [38, 42]]) # Create a 2x2 ndarray (which can be treated as a matrix)
print(array)
# Output => [[16 26][38 42]]

matrix = np.matrix(array) # Convert the array to a NumPy matrix
# Output => [[16 26][38 42]]

Here, 2-D ndarray is similar to matrix. We created an 2-D array and then using np.matrix(array) method we can convert that array into a matrix.

Create Matrix in NumPy with Zeros and Ones

We can also create a matrix with specific dimensions filled with zeros or ones using NumPy functions such as numpy.zeros() and numpy.ones().

import numpy as np

zero_matrix = np.matrix(np.zeros((3, 3))) # Create a 3x3 matrix of zeros
print("Zero Matrix:", zero_matrix)
# Output => [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]

one_matrix = np.matrix(np.ones((3, 3))) # Create a 3x3 matrix of ones
print("One Matrix:", one_matrix)
# Output => [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]

In this program, we are using np.zeros((3, 3)) and np.ones((3, 3)) to create 2-D array of zeros and ones respectively. Then we are using np.matrix() method to convert the given 2-D array into the matrix.

Create Matrix in NumPy with Random Values

We can create a matrix with random values using numpy.random.rand(). This method generates array of given dimensions with values in between 0 and 1.

import numpy as np

# Create a 2x2 matrix of random values between 0 and 1
random_matrix = np.matrix(np.random.rand(2, 2))
print("Random Matrix:", random_matrix)
# Output => Random Matrix: [[0.6021748  0.08169072] [0.79366297 0.03931574]]

Create Identity Matrix in NumPy using numpy.eye()

Create Matrix in NumPy - Identity Matrix and Diagonal Matrix
Create Matrix in NumPy – Identity Matrix and Diagonal Matrix

In NumPy, np.eye() generates a 2-D identity matrix; in other words, it helps create ones on specified diagonals and zeros elsewhere. Syntax => numpy.eye(N, M=None, k=0, dtype=float, order='C', like=None)

numpy.eye(N, M=None, k=0, dtype=float, order='C', like=None)
  • N (required) – This parameter specifies the number of rows in the identity matrix. It determines the size of the square matrix. For example, np.eye(3) will create a 3×3 matrix.
  • M (optional) – This parameter specifies the number of columns in the matrix. If not provided, the default value is N, meaning the matrix will be square. If M is provided, the resulting matrix can be a rectangular matrix instead of a square one. For instance, np.eye(3, 4) will create a 3×4 identity-like matrix, but the “identity” property is maintained only in the first 3 rows.
  • k (optional, default=0) – The diagonal on which to place the ones. The default is k=0, which places the ones on the main diagonal. k > 0 refers to the respective upper diagonal and k < 0 refers to the respective lower diagonal.
  • dtype (optional, default=float) – Specifies the data type of the returned matrix. It can be set to any valid NumPy data type, such as int, float, complex, etc.
  • order (optional, default=’C’) – This parameter determines the memory layout order. 'C' means row-major (C-style) order, while 'F' means column-major (Fortran-style) order.
  • like (optional) – It refers to a created array that is compatible with the like array.
  • Returns a 2D NumPy array (or matrix) with ones on the specified diagonal and zeros elsewhere. The shape of the returned array depends on the values of N and M.
import numpy as np

# Create a Square Identity Matrix
identity_matrix_3x3 = np.eye(3) # Creates a 3x3 Identity matrix
print(identity_matrix_3x3)
# Output => [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]

# Create a Non-Square Matrix
identity_matrix_3x4 = np.eye(3, 4) # Creates a 3x4 Identity matrix
print(identity_matrix_3x4)
# Output => [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.]]

# Create a 4x4 matrix with ones on the first diagonal above the main diagonal (k=1)
identity_matrix_4x4 = np.eye(4, k=1)
print(identity_matrix_4x4)
# Output => [[0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.] [0. 0. 0. 0.]]

# Create a 3x3 identity matrix with integer data type
identity_matrix_integer = np.eye(3, dtype=int)
print(identity_matrix_integer)
# Output => [[1 0 0] [0 1 0] [0 0 1]]

# Create a 2x3 identity matrix with complex numbers
identity_matrix_complex = np.eye(2, 3, dtype=complex)
print(identity_matrix_complex)
# Output => [[1.+0.j 0.+0.j 0.+0.j] [0.+0.j 1.+0.j 0.+0.j]]
  1. np.eye(3) creates a 3×3 Identity matrix with one’s on the main diagonal.
  2. np.eye(3, 4) creates a 3×4 Identity matrix with one’s on the diagonal and zeros elsewhere.
  3. np.eye(4, k=1) creates a 4×4 matrix with ones on the first diagonal above the main diagonal (k=1). In this case, k=1 moves the ones to the first diagonal above the main diagonal, creating a shifted identity matrix.
  4. np.eye(3, dtype=int) creates a 3×3 identity matrix with integer data type instead of the default float type.
  5. np.eye(2, 3, dtype=complex) create a 2×3 identity matrix with complex numbers, where the diagonal elements are complex numbers of the form 1 + 0j.

Create Diagonal Matrix in NumPy using numpy.diag()

The numpy.diag() function in NumPy is used to extract or create a diagonal matrix from a given array. Depending on the input, this method can serve two purposes:

  1. Extract the diagonal elements of a square matrix or a 2D array.
  2. Create a diagonal matrix where the input array’s elements are placed on the diagonal, and all other elements are set to zero.

Syntax => numpy.diag(v, k=0)

  • v (required) – This is the input array. This can be a 1-D array, from which the function creates a square matrix with the elements of the array on the diagonal OR this can be a 2-D array (square or rectangular), from which the function extracts the diagonal elements.
  • k (optional, default=0) – An integer that specifies the diagonal to extract or create. The default value is 0, which refers to the main diagonal (from top-left to bottom-right).
    • If k > 0, it extracts or creates the diagonal above the main diagonal.
    • If k < 0, it extracts or creates the diagonal below the main diagonal.
  • Returns 1-D array (when extracting the diagonal) or a 2-D array (when creating a diagonal matrix). The 2-D array will have the input array’s elements on the specified diagonal, and all other elements will be zero.
import numpy as np

# Create a diagonal matrix from a 1-D array
input_array = np.array([10, 20, 30])
diagonal_matrix = np.diag(input_array)
print(diagonal_matrix)
# Output => [[10  0  0] [ 0 20  0] [ 0  0 30]]

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Create a 3x3 2D array (matrix)
# Extract the main diagonal
diagonal_elements = np.diag(matrix)
print(diagonal_elements)
# Output => [1 5 9]

# Extract the diagonal above the main diagonal (k=1)
diagonal_above = np.diag(matrix, k=1)
print(diagonal_above)
# Output => [2 6]

# Extract the diagonal below the main diagonal (k=-1)
diagonal_below = np.diag(matrix, k=-1)
print(diagonal_below)
# Output => [4 8]

# Create a 5x5 diagonal matrix with elements on the second diagonal above the main diagonal (k=1)
input_array = np.array([10, 20, 30, 40])
diagonal_matrix = np.diag(input_array, k=1)
print(diagonal_matrix)
# Output => [[ 0 10  0  0  0] [ 0  0 20  0  0] [ 0  0  0 30  0] [ 0  0  0  0 40] [ 0  0  0  0  0]]

# Create a 3x3 diagonal matrix with complex values
input_array = np.array([1+2j, 3+4j, 5+6j])
diagonal_matrix = np.diag(input_array)
print(diagonal_matrix)
# Output => [[1.+2.j 0.+0.j 0.+0.j] [0.+0.j 3.+4.j 0.+0.j] [0.+0.j 0.+0.j 5.+6.j]]
  1. np.diag(np.array([10, 20, 30])) – Here we provide a 1-D array, np.diag() creates a square matrix with the elements of the array on the main diagonal. The np.diag() function places the elements [10, 20, 30] on the diagonal of a 3×3 matrix.
  2. np.diag(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) – Here we provide a 2-D array, np.diag() extracts the diagonal elements. By default, it extracts the main diagonal (k=0). np.diag(matrix) extracts the main diagonal [1, 5, 9] from the 3×3 matrix.
  3. We can extract diagonals above or below the main diagonal by setting the k parameter. For example, k=1 extracts the diagonal above the main diagonal, and k=-1 extracts the diagonal below the main diagonal.
    • np.diag(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), k=1) => k=1 gives the diagonal [2, 6], which is above the main diagonal.
    • np.diag(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), k=-1) => k=-1 gives the diagonal [4, 8], which is below the main diagonal.
  4. We can also create a diagonal matrix where the elements are placed above or below the main diagonal by using the k parameter.
    • np.diag(np.array([10, 20, 30, 40]), k=1) => the elements [10, 20, 30, 40] are placed on the diagonal above the main diagonal (k=1), creating a 5×5 matrix.
  5. We can specify the data type of the diagonal matrix by using the dtype parameter. This can be helpful if you want to create a matrix with integer or complex values.
    • np.diag(np.array([1+2j, 3+4j, 5+6j])) => The matrix is created with complex numbers on the diagonal, while all other elements are set to zero.

Create Lower Triangular Matrix in NumPy using numpy.tril()

The numpy.tril() function in NumPy is used to return the lower triangular part of a matrix. A lower triangular matrix is a square matrix in which all elements above the main diagonal are zero, and the elements on or below the diagonal can be non-zero. numpy.tril() zeroes out the elements above the main diagonal of the given 2-D array or matrix.

Syntax => numpy.tril(m, k=0)

  • m (required) – The input array (or matrix) from which the lower triangular part is to be extracted. This should be a 2-D array (matrix). If a 1-D array is passed, it is interpreted as a row vector, and the result will be an array with zeroed-out elements above the main diagonal.
  • k (optional, default=0) – This parameter specifies the diagonal from which to start filling with non-zero values.
    • k = 0 => The main diagonal (default); k=0 includes the main diagonal.
    • k > 0 => Diagonal above the main diagonal. k=1 includes the main diagonal and the first diagonal above it.
    • k < 0 => Diagonal below the main diagonal. k=-1 includes the diagonal one step below the main diagonal.
  • Returns 2-D array (or matrix) with the same shape as the input, but with elements above the specified diagonal set to zero.
import numpy as np

# Create a 3x3 matrix
input_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Extract the lower triangular part of the matrix (default k=0)
lower_triangle = np.tril(input_matrix)
print(lower_triangle)
# Output => [[1 0 0] [4 5 0] [7 8 9]]

# Extract the lower triangular part with k=1 (including the first diagonal above the main diagonal)
lower_triangle_k1 = np.tril(input_matrix, k=1)
print(lower_triangle_k1)
# Output => [[1 2 0] [4 5 6] [7 8 9]]

# Extract the lower triangular part with k=-1 (including the first diagonal below the main diagonal)
lower_triangle_k_minus_1 = np.tril(input_matrix, k=-1)
print(lower_triangle_k_minus_1)
# Output => [[0 0 0] [4 0 0] [7 8 0]]

# Create a 3x4 matrix (rectangular matrix)
matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Extract the lower triangular part of the matrix
lower_triangle_rectangular = np.tril(input_matrix)
print(lower_triangle_rectangular)
# Output => [[ 1  0  0  0] [ 5  6  0  0] [ 9 10 11  0]]
  1. Pass a square matrix and don’t specify k, it defaults to 0, meaning it keeps the elements on and below the main diagonal and zeros out the elements above it.
    • np.tril(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) => zeroes out the elements above the main diagonal. The elements on or below the diagonal remain intact.
  2. We can use k=1 to include elements from the first diagonal above the main diagonal.
    • np.tril(input_matrix, k=1) => In this case the first diagonal above the main diagonal is included as part of the lower triangular matrix.
  3. Using k=-1 keeps the first diagonal below the main diagonal and zeroes out the rest of the matrix.
    • np.tril(input_matrix, k=-1) => In this case the first diagonal below the main diagonal is included as part of the lower triangular matrix. Main diagonal is not part of the the lower triangular matrix.
  4. np.tril() method is mostly used with square matrices, but we can also apply it to rectangular matrices. It will still zero out elements above the main diagonal or the specified diagonal.
    • np.tril(input_matrix) works similarly to how it would on a square matrix, zeroing out the elements above the main diagonal.

Create Upper Triangular Matrix in NumPy using numpy.triu()

The np.triu() function in NumPy is used to return the upper triangular part of a matrix. A upper triangular matrix is a square matrix in which all elements below the main diagonal are zero, and the elements on or above the diagonal can be non-zero. numpy.triu() zeroes out the elements below the main diagonal of the given 2-D array or matrix.

Syntax => numpy.triu(m, k=0)

  • m (required) – The input array (or matrix) from which the upper triangular part is to be extracted. This should be a 2-D array (matrix). If a 1-D array is passed, it is interpreted as a row vector, and the result will be an array with zeroed-out elements below the main diagonal.
  • k (optional, default=0) – This parameter specifies the diagonal from which to start filling with non-zero values.
    • k = 0 => The main diagonal (default); k=0 includes the main diagonal.
    • k > 0 => Diagonal above the main diagonal. k=1 includes the main diagonal and the first diagonal above it.
    • k < 0 => Diagonal below the main diagonal. k=-1 includes the diagonal one step below the main diagonal.
  • Returns 2-D array (or matrix) with the same shape as the input, but with elements above the specified diagonal set to zero.
import numpy as np

# Create a 3x3 matrix
input_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Extract the upper triangular part of the matrix (default k=0)
upper_triangle = np.triu(input_matrix)
print(upper_triangle)
# Output => [[1 2 3] [0 5 6] [0 0 9]]

# Extract the upper triangular part with k=1 (including the first diagonal above the main diagonal)
upper_triangle_k1 = np.triu(input_matrix, k=1)
print(upper_triangle_k1)
# Output => [[0 2 3] [0 0 6] [0 0 0]]

# Extract the upper triangular part with k=-1 (including the first diagonal below the main diagonal)
upper_triangle_k_minus_1 = np.triu(input_matrix, k=-1)
print(upper_triangle_k_minus_1)
# Output => [[1 2 3] [4 5 6] [0 8 9]]

# Create a 3x4 matrix (rectangular matrix)
input_matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Extract the upper triangular part of the matrix
upper_triangle_rectangular = np.triu(input_matrix)
print(upper_triangle_rectangular)
# Output => [[ 1  2  3  4] [ 0  6  7  8] [ 0  0 11 12]]
  1. Pass a square matrix and don’t specify k, it defaults to 0, meaning it keeps the elements on and above the main diagonal and zeros out the elements above it.
    • np.triu(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) => zeroes out the elements below the main diagonal. The elements on or above the diagonal remain intact.
  2. We can use k=1 to include elements above the main diagonal but exclude the main diagonal itself.
    • np.triu(input_matrix, k=1) => In this case the first diagonal above the main diagonal is included as part of the upper triangular matrix. Main diagonal is not part of the the upper triangular matrix.
  3. Using k=-1 keeps the first diagonal below the main diagonal and zeroes out the rest of the matrix.
    • np.triu(input_matrix, k=-1) => In this case the first diagonal below the main diagonal is included as part of the upper triangular matrix. Main diagonal is also part of the the upper triangular matrix.
  4. np.triu() method is mostly used with square matrices, but we can also apply it to rectangular matrices. It will still zero out elements below the main diagonal or the specified diagonal.
    • np.triu(input_matrix) works similarly to how it would on a square matrix, zeroing out the elements below the main diagonal.

Conclusion

In this tutorial, we covered a variety of methods to create matrices in NumPy. This provides us tools to handle different types of matrix structures for our data science and computational tasks. We started with basic matrix creation techniques, such as using numpy.matrix() and numpy.array() to create matrices from lists and arrays. We also explored how to generate matrices filled with zeros and ones using numpy.zeros() and numpy.ones() respectively, which are essential for initialization purposes.

Additionally, we learned how to create matrices with random values using numpy.random.rand() and similar functions, providing you with the flexibility to simulate data for testing and modeling. We also delved into specialized matrices, such as the identity matrix using np.eye(), diagonal matrices using np.diag(), and triangular matrices using np.tril() and np.triu(). These matrix types are particularly useful in linear algebra, machine learning, and other computational fields.

Mastering these matrix creation techniques will enhance your ability to work with NumPy, allowing you to build the foundations for more complex operations and algorithms. Whether you’re performing matrix transformations, solving systems of equations, or simulating data, these matrix creation methods will serve as essential building blocks in your numerical computations.

Code snippets and programs related to Create Matrix in NumPy and other topics covered in this tutorial, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in NumPy tutorial.

Related Topics

  • numpy.meshgrid() Function – Generate Coordinate Matrices in NumPy
    In Python, numpy.meshgrid() is a useful function from the NumPy library. It is particularly useful for generating 2-Dimensional coordinate grids (or matrices) from two 1-Dimensional arrays representing the x-axes and y-axes. The generated coordinate grids are used in many applications, such as plotting 3-D surfaces, numerical computing in partial differential equations, grid based simulation in physics, solving…
  • numpy.array(): Create NumPy Arrays using Lists, Tuples and Arrays (with Example Programs)
    NumPy (Numerical Python) is one of the most powerful libraries for numerical computations, data manipulation, and analysis in Python. At the core of NumPy is the ndarray, a multi-dimensional or N-dimensional array that allows to store and manipulate large datasets efficiently. NumPy provides several ways to create arrays, from simple ones to more complex multi-dimensional…
  • numpy.arange(): Create Array of Evenly Spaced Numbers within a Range (with Example Programs)
    NumPy library provides various functions to create arrays with evenly spaced numbers within range. In previous tutorials, we learned about Key Features of NumPy Arrays in Python. In this tutorial, we will learn to create NumPy arrays using numpy.arrange() function. numpy.arange() to Create Array of Evenly Spaced Numbers within a Range numpy.arange() is used to create…
  • NumPy Array in Python: First Step into Numerical Python
    NumPy array in Python are basic entities for numerical computations. They originate from the NumPy library, an essential package in Python for scientific computing. A NumPy array also termed as ndarray, is highly efficient and an object of multi-dimensional array (N-dimensional array), which provides the base functions of numerical operations. Being NumPy Arrays an essential…
  • NumPy Array Attributes | ndarray Attributes (with Example Programs)
    NumPy (Numerical Python) is a powerful library for numerical computing in Python. It provides support for large multidimensional arrays and matrices, and it also provides a collection of mathematical functions to operate on these arrays. Understanding the attributes of NumPy arrays is essential for efficiently working with them. In previous articles, we learned about NumPy…

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *