Vector-vector multiplication to create a matrix

前端 未结 1 1521
悲哀的现实
悲哀的现实 2021-01-22 04:10

I am an IDL user slowly switching to numpy/scipy, and there is an operation that I do extremely often in IDL but cannot manage to reproduce with numpy:

IDL> a          


        
相关标签:
1条回答
  • 2021-01-22 04:50

    This is known as the outer product of two vectors. You could use np.outer:

    import numpy as np
    
    a = np.array([2, 4])
    b = np.array([3, 5])
    c = np.outer(a, b)
    
    print(c)
    # [[ 6 10]
    #  [12 20]]
    

    Assuming that both of your inputs are numpy arrays (rather than Python lists etc.) you also could use the standard * operator with broadcasting:

    # you could also replace np.newaxis with None for brevity (see below)
    d = a[:, np.newaxis] * b[np.newaxis, :]
    

    You could also use np.dot in combination with broadcasting:

    e = np.dot(a[:, None], b[None, :])
    

    Another lesser-known option is to use the .outer method of the np.multiply ufunc:

    f = np.multiply.outer(a, b)
    

    Personally I would either use np.outer or * with broadcasting.

    0 讨论(0)
提交回复
热议问题