将两个矩阵交叉串联成十个

2024-04-18 21:57:14 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,给定两个矩阵

[1 2] and [5 6]
[3 4]     [7 8],

有没有办法把它们串联起来得到下面的矩阵?你知道吗

[1 2 1 2]
[3 4 3 4]
[5 5 6 6]
[7 7 8 8]

Tags: and矩阵办法
2条回答

基于NumPy的方法

array-initialization^{}一起使用-

def assign_as_blocks(a,b):
    m1,n1 = a.shape
    m2,n2 = b.shape
    out = np.empty((m1+m2,n2,n1),dtype=int)
    out[:m1] = a[:,None,:]
    out[m1:] = b[:,:,None]
    return out.reshape(m1+m2,-1)

要使用tensorflow工具,修改后的版本是:

def assign_as_blocks_v2(a,b):
      shape1 = tf.shape(a)
      shape2 = tf.shape(b)
      m1 = shape1[0]
      n1 = shape1[1]
      m2 = shape2[0]
      n2 = shape2[1]
      p1 = tf.tile(a,[1,n2])
      p2 = tf.reshape(tf.tile(tf.expand_dims(b, 1),[1,1,n1]), [m2,-1])
      out = tf.concat((p1,p2),axis=0)
      return out

样本运行

案例1(问题样本):

In [95]: a
Out[95]: 
array([[1, 2],
       [3, 4]])

In [96]: b
Out[96]: 
array([[5, 6],
       [7, 8]])

In [97]: assign_as_blocks(a, b)
Out[97]: 
array([[1, 2, 1, 2],
       [3, 4, 3, 4],
       [5, 5, 6, 6],
       [7, 7, 8, 8]])

案例2(一般形状随机数组):

In [106]: np.random.seed(0)
     ...: a = np.random.randint(0,9,(2,3))
     ...: b = np.random.randint(0,9,(4,5))

In [107]: a
Out[107]: 
array([[5, 0, 3],
       [3, 7, 3]])

In [108]: b
Out[108]: 
array([[5, 2, 4, 7, 6],
       [8, 8, 1, 6, 7],
       [7, 8, 1, 5, 8],
       [4, 3, 0, 3, 5]])

In [109]: assign_as_blocks(a, b)
Out[109]: 
array([[5, 0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3, 5, 0, 3],
       [3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3],
       [5, 5, 5, 2, 2, 2, 4, 4, 4, 7, 7, 7, 6, 6, 6],
       [8, 8, 8, 8, 8, 8, 1, 1, 1, 6, 6, 6, 7, 7, 7],
       [7, 7, 7, 8, 8, 8, 1, 1, 1, 5, 5, 5, 8, 8, 8],
       [4, 4, 4, 3, 3, 3, 0, 0, 0, 3, 3, 3, 5, 5, 5]])
>>> a = [[1,2],[3,4]]
>>> b = [[5,6],[7,8]]
>>> np.r_[np.kron([1,1],a),np.kron(b, [1,1])]
array([[1, 2, 1, 2],
       [3, 4, 3, 4],
       [5, 5, 6, 6],
       [7, 7, 8, 8]])

相关问题 更多 >