Below is a sample code of MATLAB and its eqv Python code using Numpy package. The MATLAB code works fine but the Python code is giving issues:
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))
I get the below error:
Traceback (most recent call last):
File "a.py", line 5, in
P0 = np.dot(YDFA_P0, np.ones((1, N)))
ValueError: matrices are not aligned
How can I fix this error or rather port the Matlab code successfully to Python?
解决方案
With np.array([1,2,3,4,5]), you are creating a matrix with one row (actually, it's just a one-dimensional vector), while double([1;2;3;4;5]) is a matrix with one column. Try this:
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.]])
Alternatively, you could also do np.array([[1,2,3,4,5]]).transpose() (note the [[ ]])