w3resource

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.

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)

Sample 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.



Follow us on Facebook and Twitter for latest update.