python矩阵输出对齐_Matlab到Python代码的转换:矩阵未对齐

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值