如何用向量乘法创建矩阵

时间:2019-01-08 16:26:19

标签: python numpy

我正在尝试通过进行像x这样的矩阵乘法来从大小为2的向量x * x^T创建2x2数组:

>>> x = np.array([2, 2])
>>> x
array([2, 2])
>>> np.matmul(x,x.T)
8

如您所见,这失败了。我想出了这个解决方案:

>>> m = np.matrix(x)
>>> m
matrix([[2, 2]])
>>> m.T
matrix([[2],
        [2]])
>>> np.matmul(m.T, m)
matrix([[4, 4],
        [4, 4]])

达到我想要的目标。但是,有没有更好的方法(最好不要使用np.matrix?)?

编辑:由于问题之外的上下文,因此无法创建2x1向量。

4 个答案:

答案 0 :(得分:2)

使用np.outer

np.outer(x, x)
# array([[4, 4],
#        [4, 4]])

或者,increase x's dimension by 1在致电np.matmul之前:

x = x[:, None]  # x = x.reshape(-1, 1)
x.shape
# (2, 1)

x @ x.T  # (2,1) . (1,2) => (2,2)
# array([[4, 4],
#        [4, 4]])

答案 1 :(得分:0)

如果调整了x的形状,则可以使用@运算符进行乘法:

x = np.array([2, 2])
Xprime = x.reshape(len(x), 1)
print(Xprime @ Xprime.T)
#[[4 4]
# [4 4]]

答案 2 :(得分:0)

np.array([2, 2])不会创建2x1向量,而是创建2向量。如果需要2x1矩阵,则需要np.array([[2], [2]])。或者,您可以使用np.array([[2, 2]])创建1x2矩阵,然后执行np.matmul(x.T,x)

答案 3 :(得分:0)

您在这里没有2x1向量,而是1D向量。您可以通过以下方式看到它:

> x = np.array([[2, 2]])
> x.shape
(1,2)

要实际创建2x1向量,请添加bracets:

> np.matmul(x.T,x)
array([[4, 4],
       [4, 4]])

现在您拥有了想要的东西:

x.T@x

const path = require('path'); module.exports = { target: 'node', entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'build') }, module: { rules: [ { test: /\.js?$/, loader: 'babel-loader', exclude: /node_modules/, options: { presets: [ 'react', 'stage-0', ['env', { targets: { browsers: ['last 2 versions']}}] ] } } ] } } 在Python3中。

相关问题