Python numpy issues with array dimensions

414 Views Asked by At

I'm supposed to implement householder transformation of a matrix A $\in R^{m \times n}$, with m $\ge$ n, i.e. multiply the matrix A with matrices so that it becomes an upper triangular matrix R. AFAICS, I use the right formulas, but I'm having issues with the array dimensions. Would you mind helping me? Thanks.

Code:

# -*- coding: utf-8 -*-
import numpy

def sign(x):
    if x < 0:
        return -1
    else:
        return 1

def householder(A):
    m = A.shape[0]
    n = A.shape[1]
    if n > m:
        print "Error: n > m"
        # Error-handling here
    for k in range(n):
        x = A[k:m, k]
        e = numpy.zeros(x.shape[0])
        e[0] = 1
        v = sign(x[0])*numpy.linalg.norm(x, 2)*e + x
        v /= numpy.linalg.norm(v, 2)
        A[k:m, k:n] -= 2*numpy.multiply(numpy.matrix(v), numpy.multiply(numpy.matrix(v).T, A[k:m, k:n])) # Errors happening here
    print A

def main():
    X = numpy.array([(3, 4), (5, 6), (1, 2), (5, 6)])
    householder(X)

main()