本文介绍了numpy:从没有循环的另一个矩阵的所有元素中减去矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个分别为(m x d)和(n x d)的矩阵X,Y.现在我想从矩阵X的每个元素中减去整个矩阵Y,以获得大小为(m x n x d)的第三个矩阵Z.使用循环看起来像这样:

I have two matrices X,Y of size (m x d) and (n x d) respectively. Now i want to subtract the whole matrix Y from each element of the matrix X to get a third matrix Z of size (m x n x d). Using loops it would look this:

Z = [(Y-x) for x in X]

但是我想避免循环,仅使用numpy.

but i want to avoid loops and use numpy only.

推荐答案

如果我正确理解,这是一个小演示:

If i understand correctly, here is a small demo:

In [81]: X = np.arange(6).reshape(2,3)

In [82]: Y = np.arange(12).reshape(4,3)

In [83]: X
Out[83]:
array([[0, 1, 2],
       [3, 4, 5]])

In [84]: Y
Out[84]:
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

In [85]: X.shape
Out[85]: (2, 3)

In [86]: Y.shape
Out[86]: (4, 3)

In [87]: Z = Y - X[:, None]

结果:

In [95]: Z
Out[95]:
array([[[ 0,  0,  0],
        [ 3,  3,  3],
        [ 6,  6,  6],
        [ 9,  9,  9]],

       [[-3, -3, -3],
        [ 0,  0,  0],
        [ 3,  3,  3],
        [ 6,  6,  6]]])

In [96]: Z.shape
Out[96]: (2, 4, 3)

这篇关于numpy:从没有循环的另一个矩阵的所有元素中减去矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 10:30