Backport changes to matrix.c