简体   繁体   English

Numpy和Matlab的总​​和有何不同?

[英]Numpy and Matlab difference in sum?

I have a code that I am trying to translate from Matlab to Python however there is a problem with summation: 我有一个代码,我试图从Matlab转换为Python,但总结存在问题:

a=np.arange(1,28).reshape(3,3,3)
print a
print np.sum(np.sum(a,axis=1),axis=2)

gives me axis index out of bound error . 给我axis index out of bound error According to the answer below I am updating this example. 根据下面的答案,我正在更新这个例子。 The result for: 结果如下:

a=np.arange(1,28).reshape(3,3,3)
print a
print np.sum(np.sum(a,axis=1),axis=2)

is: 是:

[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[10 11 12]
  [13 14 15]
  [16 17 18]]

 [[19 20 21]
  [22 23 24]
  [25 26 27]]]
[ 45 126 207]

but the same code in Matlab works fine: 但是Matlab中的相同代码工作正常:

a=1:27
b=reshape(a,[3,3,3])
b(:,:,1)=b(:,:,1)';
b(:,:,2)=b(:,:,2)';
b(:,:,3)=b(:,:,3)';
b
sum(sum(b,2),3)

Will give the following output: What is the problem? 将给出以下输出:有什么问题?

b(:,:,1) =

     1     2     3
     4     5     6
     7     8     9


b(:,:,2) =

    10    11    12
    13    14    15
    16    17    18


b(:,:,3) =

    19    20    21
    22    23    24
    25    26    27

ans =

        99
       126
       153

I believe that the problem is that the result of np.sum(a, axis=1) is a 2-dimensional array. 我认为问题是np.sum(a, axis=1)是一个二维数组。 If you then try to sum that along axis=2, you'll get the error you see because a 2d array only has axes 0 and 1. 如果你然后尝试沿轴= 2求和,你会得到你看到的错误,因为2d数组只有轴0和1。

eg: 例如:

>>> a = np.ones((3,3,3))
>>> np.sum(a, axis=1)
array([[ 3.,  3.,  3.],
       [ 3.,  3.,  3.],
       [ 3.,  3.,  3.]])
>>> np.sum(a, axis=1).shape
(3, 3)
>>> np.sum(np.sum(a, axis=1), axis=1)
array([ 9.,  9.,  9.])

Your first summation is summing along the columns, which I don't think you want. 你的第一个总结是沿着列总结,我认为你不想要。

>>> np.sum(a,axis=1)
array([12, 15, 18],
      [39, 42, 45],
      [66, 69, 72]])

Instead, change the axis of the first summation. 而是,更改第一个求和的轴。 This will yield the same answer as your matlab code: 这将产生与您的matlab代码相同的答案:

>>> print np.sum(np.sum(a, axis=0), axis=1)
[99, 126, 153]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM