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

时间:2015-01-08 12:05:59

标签: python numpy

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

MATLAB /倍频程

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?

3 个答案:

答案 0 :(得分:2)

使用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()(请注意[[ ]]

答案 1 :(得分:2)

我认为您正在寻找outer product

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

答案 2 :(得分:0)

使用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.]])
>>>