how to 3-way outer product in numpy?

前端 未结 3 612
刺人心
刺人心 2021-01-21 07:42

About the numpy.outer [link] .

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product will be M*N matrix.

3条回答
  •  一向
    一向 (楼主)
    2021-01-21 08:01

    You can use numpy.ix_; it adds axes to its operands such that they form an open grid. Below the shapes of A,B,C are (2, 1, 1), (1, 3, 1) and (1, 1, 4), so just multiplying them together results in the outer product.

    a = np.arange(1, 3)
    b = np.arange(1, 4)
    c = np.arange(1, 5)
    A,B,C = np.ix_(a,b,c)
    A*B*C
    # array([[[ 1,  2,  3,  4],
    #         [ 2,  4,  6,  8],
    #         [ 3,  6,  9, 12]],
    #
    #        [[ 2,  4,  6,  8],
    #         [ 4,  8, 12, 16],
    #         [ 6, 12, 18, 24]]])
    

提交回复
热议问题