问题
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