How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

后端 未结 2 2088
悲哀的现实
悲哀的现实 2020-12-09 22:50

I found a link where it is shown with an example that the Matlab mldivide operator (\\) gives \'special\' solutions when the system of linear equat

2条回答
  •  有刺的猬
    2020-12-09 23:06

    np.array([[8],[18]]).shape
    

    is

    (2,1) 
    

    but you want

    (2,)
    
    #!/usr/bin/env python3
    import numpy as np
    from scipy.optimize import nnls
    test_A = np.array([[1,2,0],[0,4,3]])
    
    try:
        test_b = np.array([[8],[18]]) # wrong
        print(nnls(test_A,test_b))
    except Exception as e:
        print(str(e))
    
    test_b = np.array([8,18]) # sic!
    print(nnls(test_A,test_b))
    

    output:

    expected vector
    (array([ 0.        ,  4.        ,  0.66666667]), 0.0)
    

提交回复
热议问题