Python - Matrix outer product

后端 未结 4 1407
时光取名叫无心
时光取名叫无心 2020-12-14 10:54

Given two matrices

A: m * r
B: n * r

I want to generate another matrix C: m * n, with each entry C_ij being a mat

4条回答
  •  粉色の甜心
    2020-12-14 11:29

    Use numpy;

    In [1]: import numpy as np
    
    In [2]: A = np.array([[1, 2], [3, 4]])
    
    In [3]: B = np.array([[3, 1], [1, 2]])
    
    In [4]: C = np.outer(A, B)
    
    In [5]: C
    Out[5]: 
    array([[ 3,  1,  1,  2],
           [ 6,  2,  2,  4],
           [ 9,  3,  3,  6],
           [12,  4,  4,  8]])
    

    Once you have the desired result, you can use numpy.reshape() to mold it in almost any shape you want;

    In [6]: C.reshape([4,2,2])
    Out[6]: 
    array([[[ 3,  1],
            [ 1,  2]],
    
           [[ 6,  2],
            [ 2,  4]],
    
           [[ 9,  3],
            [ 3,  6]],
    
           [[12,  4],
            [ 4,  8]]])
    

提交回复
热议问题