Search code examples
pythonpython-3.xmatrixindex-errordecomposition

list index out of range - problem with using function to decompose matrix


I have tried to use this code to do a LU decomposition of nxn matrix but I keep getting 'IndexError: list index out of range'. Any idea what went wrong here and how to fix this?

import numpy as np
import pylab
from pprint import pprint

def matrixMul(A, B):
    TB = zip(*B)
    return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]

def permut(m):
    n = len(m)
    ID = [[float(i == j) for i in range(n)] for j in range(n)]
    for j in range(n):
        row = max(range(j, n), key=lambda i: abs(m[i][j]))
        if j != row:
            ID[j], ID[row] = ID[row], ID[j]
    return ID

def lu(A):
    n = len(A)
    L = [[0.0] * n for i in range(n)]
    U = [[0.0] * n for i in range(n)]
    P = permut(A)
    A2 = matrixMul(P, A)
    for j in range(n):
        L[j][j] = 1.0
        for i in range(j+1):
            s1 = sum(U[k][j] * L[i][k] for k in range(i))
            U[i][j] = A2[i][j] - s1
        for i in range(j, n):
            s2 = sum(U[k][j] * L[i][k] for k in range(j))
            L[i][j] = (A2[i][j] - s2) / U[j][j]
    return (L, U, P)

I have been trying to use the above function with following code:

a = np.array([[2, 1, 5], [4, 4, -4], [1, 3, 1]]);
for part in lu(a):
    pprint(part)
    print
print

It is supposed to return matrixes L,U,P but all i get is this error message:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-52-da52bba817aa> in <module>()
      1 a = np.array([[2, 1, 5], [4, 4, -4], [1, 3, 1]]);
----> 2 for part in lu(a):
      3     pprint(part)
      4     print
      5 print

<ipython-input-51-e49d88430e36> in lu(A)
     27         for i in range(j, n):
     28             s2 = sum(U[k][j] * L[i][k] for k in range(j))
---> 29             L[i][j] = (A2[i][j] - s2) / U[j][j]
     30     return (L, U, P)
     31     print(L)

Solution

  • I tried printing the matrix A2. I got this

    A2 = 
    [[4.0, 4.0, -4.0], [], []]
    

    Looks like matrixMul function is working incorrectly

    I replaced

    A2 = matrixMul(P, A)
    

    With this.

    A2 = np.dot(P, A)
    

    numpy.dot function is equivalent to matrix multiplication for a 2D array (i.e. a matrix)

    The error is gone.

    However, I can't tell you about the correctness of the LU decomposition answer.