Translating mathematical functions from MATLAB to Python

Question:

I am currently working on a project which involves translating a program which runs in MATLAB to Python to increase speed and efficiency. However, I have hit a stumbling block. First, I am confused as to what the tilde(~) indicates in MATLAB, and how to represent that in a corresponding way in python. Second, I have been searching through documentation and I’m also having a difficult time finding an equivalent function for the ‘sign’ function in MATLAB.

    indi = ~abs(indexd);
    wav = (sum(sum(wv)))/(length(wv)*(length(wv)-1));
    thetau = (sign(sign(wv - wav) - 0.1) + 1)/2;
    thetad = (sign(sign(wav - wv) - 0.1) + 1)/2;

I have already converted indexd, and wv, which are from a previous section of code, to numpy arrays. What is the most efficient Pythonic way to replace the ~ and sign functions?

Asked By: Brandon Ginley

||

Answers:

If you’re using numpy, then you also use ~ to invert things just like MATLAB. See: What does the unary operator ~ do in numpy?. The sign function also exists in numpy. You use numpy.sign. Therefore, the code above is simply:

>>> import numpy as np
>>> indi = ~np.abs(indexd)
>>> wav = (np.sum(wv))/(len(wv)*(len(wv)-1))
>>> thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
>>> thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2

Be advised that using length in MATLAB on matrices finds the largest dimension in the matrix whereas numpy uses len to give you the total number of rows in the matrix. Assuming that the number of rows in wv is greater than or equal to the number of columns in wv, then the above code will work as you expect. However, if you have more columns than rows, that you’d need is to find the maximum of the dimensions and use that instead… so:

>>> import numpy as np
>>> maxdim = np.max(wv.shape)
>>> indi = ~np.abs(indexd)
>>> wav = (np.sum(wv))/(maxdim*(maxdim-1))
>>> thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
>>> thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2

The above call to numpy.sum actually sums over all of the dimensions by default, so there’s no need to call nested sum calls to sum over the entire matrix (Thanks Divakar!).

Totally recommend you go here and see the awesome table and guide from translating from MATLAB to numpy: Link

Answered By: rayryeng
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.