Search code examples
pythonmatlabtranslate

dimension error while from matlab to python


i want to change the algorithm of gram schmidt_process, matlab to python but i got an error like

def qr_mgs(A):
    m, n = A.shape
    Q = A
    R = np.zeros((n, n))
    for i in range(n - 1):
        R[i, i] = np.linalg.norm(Q[:, i])
        Q[:, i] = Q[:, i] / R[i, i]
        R[i, i+1:n] = np.matmul(np.transpose(Q[:, i]), Q[:, i+1:n])
        Q[:, i+1:n] = Q[:, i+1:n] - np.matmul(Q[:, i], R[i, i+1:n])

    R[n, n] = np.linalg.norm(Q[:, n])
    Q[:, n] = Q[:, n]/R[n, n]

    return Q, R
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

what's the problem???

is it about dimension problem?


Solution

  • Try to debug code with some simple example.

    qr_mgs(np.arange(1, 10).reshape(3,3))
    

    When I debug your code, there is mismatch in dimensions in this line:

    Q[:, i+1:n] = Q[:, i+1:n] - np.matmul(Q[:, i], R[i, i+1:n])
    

    Q[:, i] has length 3, R[:, i+1:n] has length 2.

    You may have some indexing problem, I am no algebra expert so can't help you with fixing algorithm though.