Search code examples
python-3.xnumpyarray-broadcasting

idiom for getting contiguous copies


In the help of numpy.broadcst-array, an idiom is introduced. However, the idiom give exactly the same output as original command. Waht is the meaning of "getting contiguous copies instead of non-contiguous views."?

https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast_arrays.html

x = np.array([[1,2,3]])
y = np.array([[1],[2],[3]])

np.broadcast_arrays(x, y)
[array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]), array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])]

Here is a useful idiom for getting contiguous copies instead of non-contiguous views.

[np.array(a) for a in np.broadcast_arrays(x, y)]

[array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]), array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])]

Solution

  • To understand the difference try writing into the new arrays:

    Let's begin with the contiguous copies.

    >>> import numpy as np
    >>> x = np.array([[1,2,3]])
    >>> y = np.array([[1],[2],[3]])
    >>> 
    >>> xc, yc = [np.array(a) for a in np.broadcast_arrays(x, y)]
    >>> xc
    array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])
    

    We can modify an element and nothing unexpected will happen.

    >>> xc[0, 0] = 0
    >>> xc
    array([[0, 2, 3],
           [1, 2, 3],                                                                                                   
           [1, 2, 3]])
    >>> x
    array([[1, 2, 3]])
    

    Now, let's try the same with the broadcasted arrays:

    >>> xb, yb = np.broadcast_arrays(x, y)
    >>> xb
    array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])
    

    Although we only write to the top left element ...

    >>> xb[0, 0] = 0
    

    ... the entire left column will change ...

    >>> xb
    array([[0, 2, 3],
           [0, 2, 3],
           [0, 2, 3]])
    

    ... and also the input array.

    >>> x
    array([[0, 2, 3]])