Search code examples
pythonmatrixgrid-search

Use grid search to create a matrix with dimension n * 3 in Python


I want to have a matrix like this below, 3 columns, n rows. Each row sums to one.

[[0, 0, 1], [0, 0.1, 0.9], [0.1, 0.1, 0.8], [0.1, 0.2, 0.7] ...]

Is there a library for doing this?


Solution

  • You can use itertools.combinations_with_replacement to pick 2 partitions out of the 11 slots between 0.0 and 1.0:

    from itertools import combinations_with_replacement
    [[n / 10 for n in (a, b - a, 10 - b)] for a, b in combinations_with_replacement(range(11), 2)]
    

    This returns:

    [[0.0, 0.0, 1.0],
     [0.0, 0.1, 0.9],
     [0.0, 0.2, 0.8],
     [0.0, 0.3, 0.7],
     [0.0, 0.4, 0.6],
     [0.0, 0.5, 0.5],
     [0.0, 0.6, 0.4],
     [0.0, 0.7, 0.3],
     [0.0, 0.8, 0.2],
     [0.0, 0.9, 0.1],
     [0.0, 1.0, 0.0],
     [0.1, 0.0, 0.9],
     [0.1, 0.1, 0.8],
     [0.1, 0.2, 0.7],
     [0.1, 0.3, 0.6],
     [0.1, 0.4, 0.5],
     [0.1, 0.5, 0.4],
     [0.1, 0.6, 0.3],
     [0.1, 0.7, 0.2],
     [0.1, 0.8, 0.1],
     [0.1, 0.9, 0.0],
     [0.2, 0.0, 0.8],
     [0.2, 0.1, 0.7],
     [0.2, 0.2, 0.6],
     [0.2, 0.3, 0.5],
     [0.2, 0.4, 0.4],
     [0.2, 0.5, 0.3],
     [0.2, 0.6, 0.2],
     [0.2, 0.7, 0.1],
     [0.2, 0.8, 0.0],
     [0.3, 0.0, 0.7],
     [0.3, 0.1, 0.6],
     [0.3, 0.2, 0.5],
     [0.3, 0.3, 0.4],
     [0.3, 0.4, 0.3],
     [0.3, 0.5, 0.2],
     [0.3, 0.6, 0.1],
     [0.3, 0.7, 0.0],
     [0.4, 0.0, 0.6],
     [0.4, 0.1, 0.5],
     [0.4, 0.2, 0.4],
     [0.4, 0.3, 0.3],
     [0.4, 0.4, 0.2],
     [0.4, 0.5, 0.1],
     [0.4, 0.6, 0.0],
     [0.5, 0.0, 0.5],
     [0.5, 0.1, 0.4],
     [0.5, 0.2, 0.3],
     [0.5, 0.3, 0.2],
     [0.5, 0.4, 0.1],
     [0.5, 0.5, 0.0],
     [0.6, 0.0, 0.4],
     [0.6, 0.1, 0.3],
     [0.6, 0.2, 0.2],
     [0.6, 0.3, 0.1],
     [0.6, 0.4, 0.0],
     [0.7, 0.0, 0.3],
     [0.7, 0.1, 0.2],
     [0.7, 0.2, 0.1],
     [0.7, 0.3, 0.0],
     [0.8, 0.0, 0.2],
     [0.8, 0.1, 0.1],
     [0.8, 0.2, 0.0],
     [0.9, 0.0, 0.1],
     [0.9, 0.1, 0.0],
     [1.0, 0.0, 0.0]]