gpt4 book ai didi

python - Matlab转Python代码转换: Matrices are not aligned

转载 作者:行者123 更新时间:2023-11-28 22:46:06 29 4
gpt4 key购买 nike

下面是 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()(注意 [[ ]])

关于python - Matlab转Python代码转换: Matrices are not aligned,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27839769/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com