Search code examples
pythonmatrix

Generating random transition probability matrix python


I was wondering whether there is an easy way to generate a square matrix filled with random numbers in python, given some conditions:

  • the rows have to sum up to 1.
  • the values on the diagonal should be significantly higher than the other values.

This is a stochastic matrix, and generating one is possible, however the tricky part is the condition about the diagonal. e.g. for a 4x4 matrix the output should look something like this:

[[0.90, 0.03, 0.03, 0.04],
[0.01, 0.98, 0.005, 0.005],
[0.04, 0.01, 0.92, 0.03],
[0.00, 0.02, 0.03, 0.95]]

Are there good ways to generate such matrix for a variable size?


Solution

  • Here is a quick-and-dirty solution

    import random
    
    k = 4
    
    result = [[random.uniform(0, 0.1 / k) for i in range(k)] for j in range(k)]
    for j, r in enumerate(result):
        r[j] += 1 - sum(r)
    

    You may want to consider using a different random distribution and also have a look at numpy.