Skip to content

Commit 78b6d9d

Browse files
authored
[Concept Entry] NumPy: Array Broadcasting (#5885)
1 parent 94f1219 commit 78b6d9d

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
Title: 'Array Broadcasting'
3+
Description: 'Refers to the process of expanding the shape of a smaller array to match the shape of a larger array during arithmetic operations.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'NumPy'
9+
- 'Math'
10+
- 'Methods'
11+
- 'Arrays'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
In NumPy, **array broadcasting** refers to the process of expanding the shape of a smaller [array](https://www.codecademy.com/resources/docs/numpy/ndarray) to match the shape of a larger array during arithmetic operations. This is helpful when there is a need to perform mathematical operations on two arrays of different shapes.
18+
19+
## Example
20+
21+
The following example demonstrates the usage of array broadcasting:
22+
23+
```py
24+
import numpy as np
25+
26+
# Create an array of size (1 x 4)
27+
arr1 = np.array([[11, 12, 13, 14]])
28+
29+
# Create an array of size (2 x 4)
30+
arr2 = np.array([[21, 22, 23, 24], [25, 26, 27, 28]])
31+
32+
# Add the arrays
33+
res = arr1 + arr2
34+
35+
# Print the result
36+
print(res)
37+
```
38+
39+
In the above example, the shape of the smaller array `arr1` (1 x 4) is expanded to the shape of the larger array `arr2` (2 x 4) during addition. After expansion, the array `arr1` looks like `[[11, 12, 13, 14], [11, 12, 13, 14]]`.
40+
41+
The above code produces the following output:
42+
43+
```shell
44+
[[32 34 36 38]
45+
[36 38 40 42]]
46+
```
47+
48+
## Codebyte Example
49+
50+
The following codebyte example demonstrates the usage of array broadcasting:
51+
52+
```codebyte/python
53+
import numpy as np
54+
55+
# Create an array of size (1 x 3)
56+
arr1 = np.array([[31, 32, 33]])
57+
58+
# Create an array of size (2 x 3)
59+
arr2 = np.array([[41, 42, 43], [44, 45, 46]])
60+
61+
# Add the arrays
62+
res = arr1 + arr2
63+
64+
# Print the result
65+
print(res)
66+
```

0 commit comments

Comments
 (0)