Move utility functions to matrix.go