35 lines
970 B
Python
35 lines
970 B
Python
import numpy as np
|
|
"""
|
|
Demonstrates NumPy broadcasting rules with arrays of different shapes.
|
|
Examples included:
|
|
- Adding a (2, 3) array to a (1, 3) array using broadcasting.
|
|
- Adding a (2, 3) array to a (3,) array using broadcasting.
|
|
- Adding a scalar to a (2, 3) array using broadcasting.
|
|
Prints the shapes of the arrays and the results of the element-wise additions.
|
|
"""
|
|
array_1 = np.array([[1, 2, 3], [4, 5, 6]])
|
|
print(array_1.shape)
|
|
# Creating a 2D array with 1 row
|
|
array_2 = np.array([[11, 12, 13]])
|
|
print(array_2.shape)
|
|
# Broadcasting and element-wise addition
|
|
result = array_1 + array_2
|
|
print(result)
|
|
|
|
|
|
array_1 = np.array([[1, 2, 3], [4, 5, 6]])
|
|
print(array_1.shape)
|
|
# Creating a 1D array
|
|
array_2 = np.array([11, 12, 13])
|
|
print(array_2.shape)
|
|
# Broadcasting and element-wise addition
|
|
result = array_1 + array_2
|
|
print(result)
|
|
|
|
|
|
array = np.array([[1, 2, 3], [4, 5, 6]])
|
|
print(array.shape)
|
|
# Broadcasting and element-wise addition
|
|
result = array + 10
|
|
print(result)
|