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

元气小坏坏 提交于 2019-12-12 04:33:12

问题


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.


回答1:


>>> 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.




回答2:


The first floor give you the transform of python code.

but if you want to know why code:

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

give the result

[ 1.  0.]
[ 0.55051026  1.41421356]

because linalg.solve() Solve a linear matrix equation, or system of linear scalar equations.

so the code for i in range(2): print linalg.solve(sqrt(a).T, a[i, :].T).T will solve the linear matrix equations

0 * x0 + sqrt(2) * x1 = 0
1 * x0 + sqrt(3) * x1 = 1
0 * x0 + sqrt(2) * x1 = 2
1 * x0 + sqrt(3) * x1 = 3

so you will get the result

[ 1, 0].T
[ 3 - sqrt(6) , sqrt(2)].T

and in numpy shape (2L,).T is same as (2L,) so you will get the answer.



来源:https://stackoverflow.com/questions/12454685/translating-a-line-of-matlab-bsxfun-rdivide-to-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!