more optimizations of generate_d_mtrx