Skip to content Skip to sidebar Skip to footer

Matlab To Python Code Conversion: Matrices Are Not Aligned

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

Solution 1:

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 [[ ]])

Solution 2:

I think you are looking for the outer product:

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

Solution 3:

Use numpy.newaxis to align the first array:

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

Post a Comment for "Matlab To Python Code Conversion: Matrices Are Not Aligned"