pythonarraysnumpy

Can I multiply these Numpy arrays without creating an intermediary array?


This script:

import numpy as np

a = np.linspace(-2.5, 2.5, 6, endpoint=True)
b = np.vstack((a, a)).T
c = np.array([2, 1])
print(b*c)

produces:

[[-5.  -2.5]
 [-3.  -1.5]
 [-1.  -0.5]
 [ 1.   0.5]
 [ 3.   1.5]
 [ 5.   2.5]]

which is my desired output. Can it be produced directly with from a and c? Trying a*c and c*a fails due to ValueError: operands could not be broadcast together error. Trying different dimensions of c, e.g. [[2, 1]] fails, too.


I found that the simplest way to go is to define a differently, i.e. a = np.linspace([-2.5, -2.5], [2.5, 2.5], 6, endpoint=True). I can now write a*c, a*(2, 1), etc. Since it changes my initial post, all answers below remain valid.


Solution

  • With the original (6,) and (2,) arrays, einsum may make the outer product more explicit:

    In [331]: a=np.linspace(-2.5, 2.5, 6, endpoint=True); c=np.array([1,2])
    
    In [332]: np.einsum('i,j->ij',a,c)
    Out[332]: 
    array([[-2.5, -5. ],
           [-1.5, -3. ],
           [-0.5, -1. ],
           [ 0.5,  1. ],
           [ 1.5,  3. ],
           [ 2.5,  5. ]])
    

    np.outer(a,c) and np.multiply.outer(a,c) also do this.