Home > Net >  matlab sum function to python converstion
matlab sum function to python converstion

Time:07-23

I am trying to convert this matlab code to python:

#T2 = (sum((log(X(1:m,:)))'));

Here is my code in python:

T2 = sum(np.log(X[0:int(m),:]).T)

where m = 103 and X is a matrix:

f1 = np.float64(135)
f2 = np.float64(351)
X = np.float64(p[:, int(f1):int(f2)])

and p is dictionary (loaded data)

The problem is python gives me the exact same value with same dimension (216x103) like matlab before applying the sum function on (np.log(X[0:int(m), :]).T). However. after applying the sum function it gives me the correct value but wrong dimension (103x1). The correct dimension is (1x103). I have tried using transpose after getting the sum but it doesnt work. Any suggestions how to get my desired dimension?

CodePudding user response:

A matrix in MATLAB consists of m rows and n columns, but a matrix in NumPy is an array of arrays. Each subarray is a flat vector having 1 dimension equal to the number of its elements n. MATLAB doesn't have flat vectors at all, a row is 1xn matrix, a column is mx1 matrix, and a scalar is 1x1 matrix.

So, back to the question, when you write T2 = sum(np.log(X[0:int(m),:]).T) in Python, it's neither 103x1 nor 1x103, it's a flat 103 vector. If you specifically want a 1x103 matrix like MATLAB, just reshape(1,-1) and you don't have to transpose since you can sum over the second axis.

import numpy as np

X = np.random.rand(216,103)
m = 103
T2 = np.sum(np.log(X[:m]), axis=1).reshape(1,-1)
T2.shape
# (1, 103)

CodePudding user response:

Lets make a demo 2d array:

In [19]: x = np.arange(12).reshape(3,4)
In [20]: x
Out[20]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

And apply the base Python sum function:

In [21]: sum(x)
Out[21]: array([12, 15, 18, 21])

The result is a (4,) shape array (not 4x1). Print sum(x).shape if you don't believe me.

The numpy.sum function adds all terms if no axis is given:

In [22]: np.sum(x)
Out[22]: 66

or with axis:

In [23]: np.sum(x, axis=0)
Out[23]: array([12, 15, 18, 21])
In [24]: np.sum(x, axis=1)
Out[24]: array([ 6, 22, 38])

The Python sum treats x as a list of arrays, and adds them together

In [25]: list(x)
Out[25]: [array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8,  9, 10, 11])]

In [28]: x[0] x[1] x[2]
Out[28]: array([12, 15, 18, 21])

Transpose, without parameter, switch axes. It does not add any dimensions:

In [29]: x.T          # (4,3) shape
Out[29]: 
array([[ 0,  4,  8],
       [ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11]])
In [30]: sum(x).T
Out[30]: array([12, 15, 18, 21])    # still (4,) shape

Octave

>> x=reshape(0:11,4,3)'
x =

    0    1    2    3
    4    5    6    7
    8    9   10   11

>> sum(x)
ans =

   12   15   18   21

>> sum(x,1)
ans =

   12   15   18   21

>> sum(x,2)
ans =

    6
   22
   38
  • Related