I found a link where it is shown with an example that the Matlab mldivide
operator (\
) gives 'special' solutions when the system of linear equations has infinitely many solutions.
For example:
A = [1 2 0; 0 4 3];
b = [8; 18];
c_mldivide = A \ b
c_pinv = pinv(A) * b
gives the output:
c_mldivide =
0
4
0.66666666666667
c_pinv =
0.918032786885245
3.54098360655738
1.27868852459016
The solution is 'special' in the sense that the number of non-zero entries in the solution c_mldivide
is equal to rank(A)
(in this case 2). I tried the same thing in numpy using numpy.linalg.lstsq
, which gives an identical result to c_pinv
.
Is there a way to achieve the c_mldivide
solution in Python?
There was another very similar question here, but I suppose the explanation of the word 'special' was not clear enough.
Another question asked about the internal workings of the mldivide
operator, but the accepted answer doesn't seem to address this behavior.
Edit 1 : numpy
code
In [149]: test_A = np.array([[1,2,0],[0,4,3]])
test_b = np.array([[8],[18]])
np.linalg.lstsq(test_A,test_b)
Out[149]:
(array([[ 0.918 ],
[ 3.541 ],
[ 1.2787]]), array([], dtype=float64), 2, array([ 5.2732, 1.4811]))
Edit 2 : Using scipy.optimize.nnls
In[189]:
from scipy.optimize import nnls
nnls(test_A,test_b)
Out[190]:
ValueError Traceback (most recent call last)
<ipython-input-165-19ed603bd86c> in <module>()
1 from scipy.optimize import nnls
2
----> 3 nnls(test_A,test_b)
C:\Users\abhishek\Anaconda\lib\site-packages\scipy\optimize\nnls.py in nnls(A, b)
43 raise ValueError("expected matrix")
44 if len(b.shape) != 1:
---> 45 raise ValueError("expected vector")
46
47 m, n = A.shape
ValueError: expected vector