Issue Converting Matlab Code to Python when trying to sum array
Question: I am converting a Matlab code to Python but facing an issue in below lines:

Code:

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
    

And in Python:

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

But variable **P_asef_t** comparatively is coming completely incorrect:

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) 
    

How can I fix this issue?


Answer: Numpy's
[sum](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html)
function takes an additional argument `axis`, that defines over which axis of
the array is summed. The problem here is that is defaults to summing over all
axes.

In the case of a matrix such as `P_asef` you have two axes. The 0th axis are
the columns and the 1st are the rows. If you only want to sum along columns,
you need to tell `sum` to only sum over `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)
    

