Skip to content Skip to sidebar Skip to footer

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(@rd

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

Solution 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 = 01 * x0 + sqrt(3) * x1 = 10 * x0 + sqrt(2) * x1 = 21 * 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.

Post a Comment for "Translating A Line Of Matlab (bsxfun, Rdivide) To Python"