Advanced NumPy Exercises - Stack a 3x3 identity matrix vertically and horizontally
NumPy: Advanced Exercise-2 with Solution
Write a NumPy program to create a 3x3 identity matrix and stack it vertically and horizontally.
Here, you can create a 3x3 identity matrix using numpy. identity, which generates a square matrix with ones on the diagonal and zeros elsewhere. To stack this identity matrix vertically and horizontally, you can use the numpy.vstack and numpy.hstack functions, respectively. These functions allow you to concatenate arrays along different axes, resulting in larger composite matrices.
Sample Solution:
Python Code:
import numpy as np
# creating a 3x3 identity matrix
matrix = np.identity(3)
print("3x3 identity matrix:")
print(matrix)
# stacking the matrix vertically
vert_stack = np.vstack((matrix, matrix, matrix))
# stacking the matrix horizontally
horz_stack = np.hstack((matrix, matrix, matrix))
print("Vertical Stack:\n", vert_stack)
print("Horizontal Stack:\n", horz_stack)
Output:
3x3 identity matrix: [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] 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.]] 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.]]
Explanation:
In the above exercise -
matrix = np.identity(3): This creates a 3x3 identity matrix using the np.identity() function from NumPy. An identity matrix is a square matrix with 1's along the diagonal and 0's everywhere else.
vert_stack = np.vstack((matrix, matrix, matrix)): This uses the np.vstack() function to vertically stack three copies of the matrix array created in the previous line. The result is a 9x3 array.
horz_stack = np.hstack((matrix, matrix, matrix)): This line uses the np.hstack() function to horizontally stack three copies of the matrix array. The result is a 3x9 array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Dot product of two arrays of different dimensions.
Next: Find the sum of a 4x4 array containing random values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/advanced-numpy-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics