简体   繁体   English

如何在numpy中构造向量的所有可能差异的矩阵

[英]How to construct a matrix of all possible differences of a vector in numpy

I have a one dimensional array, lets say:我有一个一维数组,可以说:

import numpy as np
inp_vec = np.array([1, 2, 3])

Now, I would like to construct a matrix of the form现在,我想构造一个形式的矩阵

[[1 - 1, 1 - 2, 1 - 3],
 [2 - 1, 2 - 2, 2 - 3],
 [3 - 1, 3 - 2, 3 - 3]])

Of course it can be done with for loops but is there a more elegant way to do this?当然,它可以用 for 循环来完成,但有没有更优雅的方法来做到这一点?

这我也找到了一个很好的方法:

np.subtract.outer([1,2,3], [1,2,3])

This seems to work:这似乎有效:

In [1]: %paste
import numpy as np
inp_vec = np.array([1, 2, 3])

## -- End pasted text --

In [2]: inp_vec.reshape(-1, 1) - inp_vec
Out[2]: 
array([[ 0, -1, -2],
       [ 1,  0, -1],
       [ 2,  1,  0]])

Explanation:解释:

You first reshape the array to nx1 .您首先将数组重塑为nx1 When you subtract a 1D array, they are both broadcast to nxn :当您减去一维数组时,它们都会广播到nxn

array([[ 1,  1,  1],
       [ 2,  2,  2],
       [ 3,  3,  3]])

and

array([[ 1,  2,  3],
       [ 1,  2,  3],
       [ 1,  2,  3]])

Then the subtraction is done element-wise, which yields the desired result.然后按元素进行减法,从而产生所需的结果。

import numpy as np
inp_vec = np.array([1, 2, 3])

a, b = np.meshgrid(inp_vec, inp_vec)
print(b - a)

Output:输出:

Array([[ 0 -1 -2],
       [ 1  0 -1],
       [ 2  1  0]])

Using np.nexaxis使用 np.nexaxis

import numpy as np
inp_vec = np.array([1, 2, 3])

output = inp_vec[:, np.newaxis] - inp_vec

Output输出

array([[ 0, -1, -2],
       [ 1,  0, -1],
       [ 2,  1,  0]])

This is a quick and simple alternative.这是一种快速而简单的替代方法。

import numpy as np
inp_vec = np.array([1, 2, 3])

N = len(inp_vec)
np.reshape(inp_vec,(N,1)) - np.reshape(inp_vec,(1,N))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 numpy:如何从矩阵向量构造向量矩阵 - numpy: how to construct a matrix of vectors from vector of matrix 如何在numpy中优雅地构造以下矩阵? - How to construct the following matrix elegantly in numpy? 在numpy.linalg模块中如何实现矩阵/矢量点乘法? - How could this matrix / vector dot multiplication be possible in numpy.linalg module? 如何将向量连接到 numpy 矩阵的行中? - How to concatenate a vector into rows of a numpy matrix? 如何使用 numpy 计算向量和矩阵的“克罗内克积” - How to calculate “Kronecker Product” of a vector and a matrix with numpy 如何在 NumPy 中构建设计矩阵(用于线性回归)? - How do I construct design matrix in NumPy (for linear regression)? numpy-在固定距离处计算数组中所有可能的差异 - Numpy - compute all possible differences in an array at fixed distance 如何构造一个简单的矩阵并根据方程(numpy)更改值? - How to construct a simple matrix and change values according to equation (numpy)? 从计算运算符/矩阵向量积的代码构造(稀疏)NumPy 数组? - Construct (sparse) NumPy array from code that computes the operator/matrix-vector product? 如何在张量流中为矩阵中每个行向量构造成对差平方? - How to construct square of pairwise difference for each row vector in a matrix in tensorflow?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM