replaced matrix generation with optimized version