1
votes

I wan to create random test instances for some piece of code, which relies on sparse positive semi-definite matrices.

Matlab has the function sprandsym(n,density,rc), which creates random sparse symmetric matrices with eigenvalues rc, so a nonnegative vector rc leads to a PSD matrix.

Is there a way to recreate this function in python?

I found various solutions to either create a random sparse matrix or a random PSD matrix. I also found a solution for the combination of both by creating a random sparse matrix and, if it is not PSD, adding the identity matrix until it is PSD (namely the absolute value of the smallest eigenvalue times). But this solution creates diagonally dominant matrices, which unfortunately is not sufficient for my needed test instances.

1

1 Answers

0
votes

You can use the function provided by this answer which relys on scipy and numpy and should give you what you need:

def sprandsym(n, density):
    rvs = stats.norm().rvs
    X = sparse.random(n, n, density=density, data_rvs=rvs)
    upper_X = sparse.triu(X) 
    result = upper_X + upper_X.T - sparse.diags(X.diagonal())
    return result