chris
chris

Reputation: 4996

matlab to python lu decomposition different

I'm converting some MATLAB code to Python and am observing large numerical discrepancies between the \ operator and scipy.linalg.lstsq, which apparently are interchangeable.

In my code I calculate the LU decomposition of some matrix, however Python and Matlab give slightly different answers for 'L'.

Given this input matrix, B:

B =  [7.6822         0   -1.0000         0;
     0    0.2896   -1.0000         0;
    -6.4018         0         0   -1.0000;
     0   -0.9350         0   -1.0000]

In Python, using P,L,U = scipy.linalg.lu(B):

L = [ 1.          0.          0.          0.        ]
 [ 0.          1.          0.          0.        ]
 [ 0.         -0.30972791  1.          0.        ]
 [-0.83333333 -0.          0.83333333  1.        ]

With Matlab [L,U] = lu(B):

    L =  1.0000         0         0         0
         0   -0.3097    1.0000         0
        -0.8333         0    0.8333    1.0000
         0    1.0000         0         0

In both cases U is this:

U = [ 7.6822128   0.         -1.          0.        ]
    [ 0.         -0.93502772  0.         -1.        ]
    [ 0.          0.         -1.         -0.30972791]
    [ 0.          0.          0.         -0.74189341]

Upvotes: 0

Views: 728

Answers (2)

24b4Jeff
24b4Jeff

Reputation: 87

Notice that scipy.linalg.lu() has the optional parameter permute_l set to False. You can either set it to True, e.g. (L,U) = scipy.linalg.lu(A,permute_l=True)

or alternatively performing the permutation yourself afterwards, e.g.,

(P,L,U) = scipy.linalg.lu(A) L = P@L

Upvotes: 0

chris
chris

Reputation: 4996

So I figured it out...in MATLAB, [L,U] = lu(A) returns L already premultiplied by permutation matrix P.

Upvotes: 1

Related Questions