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.
Python: Tips of the Day
Decapitalizes the first letter of a string:
Example:
def tips_decapitalize(s, upper_rest=False): return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:]) print(tips_decapitalize('PythonTips')) print(tips_decapitalize('PythonTips', True))
Output:
pythonTips pYTHONTIPS
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook