Search code examples
pythonmatlabnumpybsxfun

Translating a line of Matlab (bsxfun, rdivide) to Python


I am translating a Matlab function to Python. Unfortunately I am not a Matlab expert and it is hard for me to understand some lines, e. g. this one:

a = [[0, 1]; [2, 3]]
bsxfun(@rdivide, sqrt(a), a)

I did not really understand it yet, but I think this line does

r / a

for each row r of sqrt(a) (or is it each column?) and r / sqrt(a) can usually be translated to numpy as

numpy.linalg.solve(sqrt(a).T, r.T).T

The problem with this is: Matlab says the result is

       NaN   1.00000
   0.70711   0.57735

and numpy says it is

[ 1.  0.]
[ 0.55051026  1.41421356]

which was generated by

for i in range(2): print linalg.solve(sqrt(a).T, a[i, :].T).T

Where is the error? The matrices sqrt(a) and a are just examples. You can replace them by any other matrix. I am just trying to understand what bsxfun does with rdivide.


Solution

  • >>> import numpy as np
    >>> a = np.array([[0,1],[2,3]])
    >>> a
    array([[0, 1],
           [2, 3]])
    >>> b = np.sqrt(a)
    >>> b/a
    Warning: invalid value encountered in divide
    array([[        nan,  1.        ],
           [ 0.70710678,  0.57735027]])
    >>>
    

    Since you need an element-wise division, not matrix multiplication by the inverse, numpy.linalg is not what you want.