Search code examples
pythonnumpyinverse

Inverse of numpy.dot


I can easily calculate something like:

R = numpy.column_stack([A,np.ones(len(A))]) 
M = numpy.dot(R,[k,m0])

where A is a simple array and k,m0 are known values.

I want something different. Having fixed R, M and k, I need to obtain m0. Is there a way to calculate this by an inverse of the function numpy.dot()? Or it is only possible by rearranging the matrices?


Solution

  • M = numpy.dot(R,[k,m0])
    

    is performing matrix multiplication. M = R * x.

    So to compute the inverse, you could use np.linalg.lstsq(R, M):

    import numpy as np
    A = np.random.random(5)
    R = np.column_stack([A,np.ones(len(A))]) 
    k = np.random.random()
    m0 = np.random.random()
    M = R.dot([k,m0])
    
    (k_inferred, m0_inferred), residuals, rank, s = np.linalg.lstsq(R, M)
    
    assert np.allclose(m0, m0_inferred)
    assert np.allclose(k, k_inferred)
    

    Note that both k and m0 are determined, given M and R (assuming len(M) >= 2).