Search code examples
arrayspython-3.xnumpynumpy-ndarraynumpy-einsum

Numpy make the product between all elemens and then insert into a triangular 2d array


Suppose we got a 1D array below

arr = np.array([a,b,c])

The first thing I need to do is the make the product of all of the elments, i.e

[ab,ac,bc]

Then construct a 2d triangular array with this element

[
[a,ab,ac],
[0,b,bc],
[0,0,c]
]


Solution

  • Create a diagonal with your 1-D array and fill the upper triangle of it with upper triangle of outer:

    out = np.diag(arr)
    #upper triangle indices
    uidx = np.triu_indices(arr.size,k=1)
    #replacing upper triangle with outer
    out[uidx]=np.outer(arr,arr)[uidx]