Matlab到Python代码的转换:矩阵未对齐 [英] Matlab to Python code conversion: Matrices are not aligned

查看:164
本文介绍了Matlab到Python代码的转换:矩阵未对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是使用Numpy软件包的MATLAB及其eqv 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

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?

How can I fix this error or rather port the Matlab code successfully to Python?

推荐答案

使用np.array([1,2,3,4,5]),您将使用一个创建一个矩阵(实际上,它只是一维向量),而double([1;2;3;4;5])是具有一个的矩阵.试试这个:

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

或者,您也可以执行np.array([[1,2,3,4,5]]).transpose()(请注意[[ ]])

Alternatively, you could also do np.array([[1,2,3,4,5]]).transpose() (note the [[ ]])

这篇关于Matlab到Python代码的转换:矩阵未对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆