rewrite matrix generator so it finishes in reasonable time for large n