Fix bug on generating matrix from flattened array