Now generates a triangular matrix, avoiding redundant computations.