Search code examples
pythonadjacency-matrixeigenvalue

How do i plot the largest eigenvalues for randomly generated matrix?


im trying to plot the eigenvalues of randomly generated adjacency matrices to obtain what looks like a gaussian distribution, im trying to change and fix the probability that the graphs are generated and plot the largest eigenvalue by its frequency, however im not sure how to do these two, here is my code:

import numpy as np
import random
import matplotlib.pyplot as plt
import scipy.linalg as la

print("Please input the amount of times you want to repeat this: ")
userInput = int(input())
print("This will repeat {} times".format(userInput))
print("--------------------------------------------")
largestEig = []


for x in range(userInput):
    n = 3
    print("Random number is: {}".format(n))
    adjMatrix = np.random.randn(0,2,(n,n))
    np.fill_diagonal(adjMatrix, 0)
    i_lower = np.tril_indices(n, -1)
    adjMatrix[i_lower] = adjMatrix.T[i_lower]
    eigvals, eigvecs = la.eig(adjMatrix)
    m = max(eigvals)
    largestEig.append(m)
    print("For {}, M = {}".format(n, m))
    
    print(adjMatrix)
    
print("---------------------------------------------")
print("The List:")
print(largestEig)



plt.plot(largestEig)
plt.show()

Solution

  • When trying to run your code, I get an error in the line that generates the matrix.

    I assume you want to create a square matrix with random values.

    In this case you might want to look at np.random.uniform:

    n=3
    adjMatrix = np.random.uniform(0,10,(n,n)) 
    

    For the plotting of the distribution, you might want to look at plt.hist():

    plt.hist(largestEig, bins=50)
    

    Adding these changes, and removing the input and print statements gives this:

    largestEig = []
    
    userInput=10000
    for x in range(userInput):
        n = 3
        adjMatrix = np.random.uniform(0,10,(n,n))
        np.fill_diagonal(adjMatrix, 0)
        i_lower = np.tril_indices(n, -1)
        adjMatrix[i_lower] = adjMatrix.T[i_lower]
        eigvals, eigvecs = la.eig(adjMatrix)
        m = max(eigvals)
        largestEig.append(m)
    
    
    
    plt.hist(largestEig, bins=50)
    plt.show()
    

    enter image description here