# Matrix Inversion

Posted by lhartmann
 Matrix Inversion June 11, 2016 11:47AM Registered: 3 years ago Posts: 91
Sometime ago I wrote a small set of functions for construction and use transformation matrices, including matrix inversion. Here is the code: [github.com]

Matrix inversion code works most of the time, except I just detected a bug I can not solve. A simple dual rotation matrix, 90º around Y then 90º around Z, is yielding nan+inf on all elements of the inverse. Works nicely for other angles, though...

M = m4rz(90) * m4ry(90); // Rotates around Y first, then Z
Minv = m4inv(M); // Fails

I managed to narrow it down to m4inv_solve(...) which does diagonal zero detection.

M = m4rz(90)*m4ry(90); // Test matrix
echo( // Failing
m4inv_solve(0, // Solve row 0: Detect diagonal zero, swap rows, calls solve2(...).
m4inv_mx(M) // Expand to Row-Reduced Echelon Format
)
);
echo( // Working by bypassing m4inv_solve(...)
m4inv_solve2(0, // Solve row 0 (normalize, scale and subtract from all other rows)
m4inv_rowswap(0,2, // Swap rows 0 and 2 by hand
m4inv_mx(M) // Expand to Row-Reduced Echelon Format
)
)
);

I looked at the code for m4inv_solve(...) for a while, but don't get why it is failing... Any ideas?

// Solve one step, ensure nonzero at diagonal element.
function m4inv_zero(x) = abs(x) < 1e-5;
function m4inv_solve(i,mx) =
!m4inv_zero(mx[ i ][i  ]) ? m4inv_solve2(i,                     mx ) :
i+1<4 && !m4inv_zero(mx[ i ][i+1]) ? m4inv_solve2(i, m4inv_rowswap(i,i+1,mx)) :
i+2<4 && !m4inv_zero(mx[ i ][i+2]) ? m4inv_solve2(i, m4inv_rowswap(i,i+2,mx)) :
i+3<4 && !m4inv_zero(mx[ i ][i+3]) ? m4inv_solve2(i, m4inv_rowswap(i,i+3,mx)) :
m4identity(); // Singular matrix, reset to identity
 Re: Matrix Inversion June 11, 2016 09:28PM Registered: 3 years ago Posts: 91
Solved: I mixed up row and column indexes while looking for a suitable row for swapping...

function m4inv_solve(i,mx) =
!m4inv_zero(mx[i  ][ i ]) ? m4inv_solve2(i,                     mx ) :
i+1<4 && !m4inv_zero(mx[i+1][ i ]) ? m4inv_solve2(i, m4inv_rowswap(i,i+1,mx)) :
i+2<4 && !m4inv_zero(mx[i+2][ i ]) ? m4inv_solve2(i, m4inv_rowswap(i,i+2,mx)) :
i+3<4 && !m4inv_zero(mx[i+3][ i ]) ? m4inv_solve2(i, m4inv_rowswap(i,i+3,mx)) :
m4identity(); // Singular matrix, reset to identity

Edited 1 time(s). Last edit at 06/11/2016 09:29PM by lhartmann.
Sorry, only registered users may post in this forum.