How to divide (1*3) vector by a (3*3) matrix using Numpy? a/b does not work

Viewed 74
a = np.array([[0.1562,0.0774,0.0702]])
b = np.array([
[0.0365,0.0191,0.0217],
[0.0191,0.0331,0.0292],
[0.0217,0.0292,0.0591]])

The output in MATLAB (desired output) is:

 4.4911    0.2724   -0.5958

The output I get in Python is:

4.27945205 4.05235602 3.23502304
8.17801047 2.33836858 2.40410959
7.19815668 2.65068493 1.18781726

The code I am using in Python is:

a/b

I have also tried np.divide(a,b) but they all give the same output which is not what I want. Is it something with '/' vs './' in MATLAB

What should my code in Python be to obtain the same output as in MATLAB?

1 Answers

You can solve this system with numpy.linalg.lstsq

import numpy as np
    
a = np.array([[0.1562,0.0774,0.0702]])
b = np.array([
        [0.0365,0.0191,0.0217],
        [0.0191,0.0331,0.0292],
        [0.0217,0.0292,0.0591]])
        
        
x = np.linalg.lstsq(b.T,a.T)
print(x)

Result:

(array([[ 4.49111376],
       [ 0.2724206 ],
       [-0.59580119]]), array([], dtype=float64), 3, array([0.09268238, 0.02342602, 0.0125916 ]))

As pointed out by @WarrenWeckesser, for this problem, np.linalg.solve will also work, similar syntax to above

Related