将Matlab(bsxfun,rdivide)行转换为Python [英] Translating a line of Matlab (bsxfun, rdivide) to Python
问题描述
我正在将Matlab函数转换为Python。不幸的是,我不是Matlab专家,所以我很难理解一些内容,例如。 G。这个:
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
对于sqrt(a)的每一行r(或者是每一列?)和r / sqrt(a)通常可以转换为numpy as
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
问题是:Matlab说结果是
The problem with this is: Matlab says the result is
NaN 1.00000
0.70711 0.57735
numpy表示这是
[ 1. 0.]
[ 0.55051026 1.41421356]
是由
for i in range(2): print linalg.solve(sqrt(a).T, a[i, :].T).T
错误在哪里?矩阵sqrt(a)和a只是示例。您可以将它们替换为任何其他矩阵。我只是想了解bsxfun对rdivide的作用。
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.
推荐答案
>>> 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]])
>>>
因为您需要按元素划分,而不是矩阵乘以逆, numpy.linalg
不是你想要什么。
Since you need an element-wise division, not matrix multiplication by the inverse, numpy.linalg
is not what you want.
这篇关于将Matlab(bsxfun,rdivide)行转换为Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!