Substitution of matrices over rings