问题在尝试对数组求和时将Matlab代码转换为Python

时间:2015-02-02 06:13:25

标签: python numpy

我正在将Matlab代码转换为Python,但在下面的行中面临一个问题:

代码:

Matlab的:

P_asef_t = sum(P_asef);
P_aseb_t = sum(P_aseb);

的Python:

import numpy as np
import scipy

P_asef_t = np.sum(P_asef)
P_aseb_t = np.sum(P_aseb)

Matlab的

whos P_asef
Variables in the current scope:

   Attr Name        Size                     Bytes  Class
   ==== ====        ====                     =====  ===== 
        P_asef     51x1200                  489600  double

Total is 61200 elements using 489600 bytes

在Python中:

(Pdb) P_asef.shape, P_asef.size
((51, 1200), 61200)

但变量 P_asef_t 相对来说完全不正确:

MATLAB:

debug> whos P_asef_t
Variables in the current scope:

   Attr Name          Size                     Bytes  Class
   ==== ====          ====                     =====  ===== 
        P_asef_t      1x1200                    9600  double

Total is 1200 elements using 9600 bytes

debug>  P_asef_t
P_asef_t =

 Columns 1 through 6:

   1.2208e-11   9.9358e-03   9.8720e-03   9.8087e-03   9.7457e-03   9.6831e-03

 Columns 7 through 12:

   9.6210e-03   9.5592e-03   9.4978e-03   9.4368e-03   9.3762e-03   9.3160e-03

 Columns 13 through 18:

的Python:

(Pdb) P_asef_t
1.3898510532602344
(Pdb) P_asef_t.shape, P_asef_t.size
((), 1)
(Pdb) 

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

Numpy的sum函数接受一个额外的参数axis,它定义了数组的哪个轴相加。这里的问题是默认是对所有轴进行求和。

对于P_asef这样的矩阵,你有两个轴。第0轴是列,第1轴是行。如果您只想对列进行求和,则需要告诉sum仅对axis=0求和。

import numpy as np

mat = np.ones((51,1200))
mat1 = np.sum(mat,axis=0)
mat2 = np.sum(mat,axis=1)
mat3 = np.sum(mat)