Matlab 到 Python 代码转换:矩阵未对齐

Matlab to Python code conversion: Matrices are not aligned

下面是 MATLAB 的示例代码及其使用 Numpy 包的 eqv Python 代码。 MATLAB 代码工作正常,但 Python 代码出现问题:

MATLAB/OCTAVE

N=1200
YDFA_P0 = double([1;2;3;4;5])
P0=YDFA_P0 *ones(1, N)


octave:27> whos P0
Variables in the current scope:

   Attr Name        Size                     Bytes  Class
   ==== ====        ====                     =====  ===== 
        P0          5x1200                   48000  double

Total is 6000 elements using 48000 bytes

Python

import numpy as np
import scipy
N=1200
YDFA_P0 = np.array([1,2,3,4,5])
P0 = np.dot(YDFA_P0, np.ones((1, N)))
P0 = YDFA_P0 * np.ones((1, N))

我收到以下错误:

Traceback (most recent call last):
  File "a.py", line 5, in <module>
    P0 = np.dot(YDFA_P0, np.ones((1, N)))
ValueError: matrices are not aligned

如何修复此错误或将 Matlab 代码成功移植到 Python?

使用 np.array([1,2,3,4,5]),您创建的矩阵只有 (实际上,它只是一个一维向量),而 double([1;2;3;4;5]) 是一个具有一 的矩阵。试试这个:

In [14]: YDFA_P0 = np.array([[1],[2],[3],[4],[5]])
In [15]: np.dot(YDFA_P0, np.ones((1,5)) )
Out[15]: 
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 3.,  3.,  3.,  3.,  3.],
       [ 4.,  4.,  4.,  4.,  4.],
       [ 5.,  5.,  5.,  5.,  5.]])

或者,您也可以 np.array([[1,2,3,4,5]]).transpose()(注意 [[ ]]

我认为您正在寻找 outer product:

>>> P0 = np.outer(YDFA_P0, np.ones(N))
>>> P0.shape
(5, 1200)

使用numpy.newaxis对齐数组:

import numpy as np

>>> a = np.array([1,2,3,4,5])
>>> b = a[:, np.newaxis]
>>> print b
[[1]
 [2]
 [3]
 [4]
 [5]]
>>> c = np.ones((1,5))
>>> print c
[[ 1.  1.  1.  1.  1.]]
>>> np.dot(b, c)
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 2.,  2.,  2.,  2.,  2.],
       [ 3.,  3.,  3.,  3.,  3.],
       [ 4.,  4.,  4.,  4.,  4.],
       [ 5.,  5.,  5.,  5.,  5.]])
>>>