Search code examples
pythonmatrixhistogramlinear-algebrastochastic

Making histogram out of matrix entries?


Today my task is to make a histogram to represent the operation of A^n where A is a matrix, but only for specific entries in the matrix.

For example, say I have a matrix where the rows sum to one. The first entry is some specific decimal number. However, if I raise that matrix to the 2nd power, that first entry becomes something else, and if I raise that matrix to the 3rd power, it changes again, etc - ad nauseum, and that's what I need to plot.

Right now my attempt is to create an empty list, and then use a for loop to add the entries that result from matrix multiplication to the list. However, all that it does is print the result from the final matrix multiplication into the list, rather than printing its value at each iteration.

Here's the specific bit of code that I'm talking about:

print("The intial probability matrix.")

print(tabulate(matrix))

baseprob = []

for i in range(1000):

     matrix_n = numpy.linalg.matrix_power(matrix, s)

     baseprob.append(matrix_n.item(0))

print(baseprob)

print("The final probability matrix.")

print(tabulate(matrix_n))

Here is the full code, as well as the output I got.

http://pastebin.com/EkfQX2Hu


Solution

  • Of course it only prints the final value, you are doing the same operation, matrix^s, 1000 times. You need to have s change each of those 1000 times.

    If you want to calculate all values in location matrix(0) for matrix^i where i is each value from 1 to s (your final power) do:

    baseprob = []
    
    for i in range(1,s): #changed to do a range 1-s instead of 1000
    
         #must use the loop variable here, not s (s is always the same)
         matrix_n = numpy.linalg.matrix_power(matrix, i)
    
         baseprob.append(matrix_n.item(0))
    

    Then baseprob will hold matrix(0) for matrix^1, matrix^2, etc. all the way to matrix^s.