From f282e311035bd43bf99380d68e2723fa092f186b Mon Sep 17 00:00:00 2001 From: David Rotermund <54365609+davrot@users.noreply.github.com> Date: Wed, 27 Dec 2023 16:27:42 +0100 Subject: [PATCH] Update README.md Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com> --- numpy/broadcasting/README.md | 46 +++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/numpy/broadcasting/README.md b/numpy/broadcasting/README.md index 6740127..63b4163 100644 --- a/numpy/broadcasting/README.md +++ b/numpy/broadcasting/README.md @@ -14,7 +14,7 @@ Questions to [David Rotermund](mailto:davrot@uni-bremen.de) ## [General broadcasting rules](https://numpy.org/devdocs/user/basics.broadcasting.html) -> When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimension and works its way left. **Two dimensions are compatible when** +> When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. ***rightmost***) dimension and works its way left. **Two dimensions are compatible when** > > * **they are equal**, or > * **one of them is 1**. @@ -40,3 +40,47 @@ Figure 3 (from [numpy.org](https://numpy.org/devdocs/user/basics.broadcasting.ht Figure 4 (from [numpy.org](https://numpy.org/devdocs/user/basics.broadcasting.html)) : In some cases, broadcasting stretches both arrays to form an output array larger than either of the initial arrays. +## [Examples](https://numpy.org/devdocs/user/basics.broadcasting.html#broadcastable-arrays) + +Good: + +```python +Image (3d array): 256 x 256 x 3 +Scale (1d array): 3 +Result (3d array): 256 x 256 x 3 + +A (4d array): 8 x 1 x 6 x 1 +B (3d array): 7 x 1 x 5 +Result (4d array): 8 x 7 x 6 x 5 + +A (2d array): 5 x 4 +B (1d array): 1 +Result (2d array): 5 x 4 + +A (2d array): 5 x 4 +B (1d array): 4 +Result (2d array): 5 x 4 + +A (3d array): 15 x 3 x 5 +B (3d array): 15 x 1 x 5 +Result (3d array): 15 x 3 x 5 + +A (3d array): 15 x 3 x 5 +B (2d array): 3 x 5 +Result (3d array): 15 x 3 x 5 + +A (3d array): 15 x 3 x 5 +B (2d array): 3 x 1 +Result (3d array): 15 x 3 x 5 +``` + +Bad: + +```python +A (1d array): 3 +B (1d array): 4 # trailing dimensions do not match + +A (2d array): 2 x 1 +B (3d array): 8 x 4 x 3 # second from last dimensions mismatched +``` +