Alternate version of build_dense_matrix wih no SQL in for loop