Home »
Python »
Python Programs
NumPy - Stack a 3x3 identity matrix vertically and horizontally
By IncludeHelp Last updated : December 13, 2023
Problem statement
Write a Python program to stack a NumPy 3x3 identity matrix vertically and horizontally.
Prerequisites
To understand the given solution, you should know about the following Python topics:
Stack a 3x3 identity matrix vertically and horizontally
To stack a 3x3 identity matrix vertically, use numpy.vstack() method (which stacks the arrays in sequence vertically (row wise).), and to stack it horizontally, use numpy.hstack() method (which stacks the arrays in sequence horizontally (column wise).). To create a 3x3 identity matrix, use numpy.identity() method. In both of the methods hstack() and vstack(), you need to pass the identity matrix three times (as a tuple).
Below are the syntaxes of numpy.vstack() and numpy.hstack() methods:
numpy.vstack(tup, *, dtype=None, casting='same_kind')
numpy.hstack(tup, *, dtype=None, casting='same_kind')
Python program to stack a 3x3 identity matrix vertically and horizontally
Create a 3x3 identity matrix, and stack it vertically and horizontally.
# Importing numpy library
import numpy as np
# Creating a 3x3 identity matrix
iMatrix = np.identity(3)
# Printing the matrix
print("3x3 identity matrix (iMatrix) is:\n")
print(iMatrix)
# Stacking the iMatrix vertically
vStack = np.vstack((iMatrix, iMatrix, iMatrix))
# Stacking the iMatrix horizontally
hStack = np.hstack((iMatrix, iMatrix, iMatrix))
# Printing the stacked matrices
print("\n3x3 Identity Matrix (Vertical Stack):\n", vStack)
print("\n3x3 Identity Matrix (Horizontal Stack):\n", hStack)
Output
The output of the above program is:
3x3 identity matrix (iMatrix) is:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
3x3 Identity Matrix (Vertical Stack):
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
3x3 Identity Matrix (Horizontal Stack):
[[1. 0. 0. 1. 0. 0. 1. 0. 0.]
[0. 1. 0. 0. 1. 0. 0. 1. 0.]
[0. 0. 1. 0. 0. 1. 0. 0. 1.]]
Code Explanation
- To use NumPy in the program, we imported the numpy module.
- Created a 3x3 identity matrix (iMatrix) by using the np.identity() method and printed it.
- Then, to stack this 3x3 identity matrix vertically and horizontally, we used np.vstack() and np.hstack() methods.
- Finally, printed both of the results (vStack and hStack).
Python NumPy Programs »