MOD move generating matrix out of the loop