Fixed bugs in matrix allocation and matrix manipulations