Search code examples
pythonmatrixmatrix-multiplication

how to multiply two matrices using numpy in iterative manner. for given range in python


I want to calculate a resultant State Matrix by multiplying initial state matrix and transition matrix for given amount of time.

For example if period is 1 month, then State1 [matrix] will be State[]*Transition[]
If period is 2 then State2[] = State1[]*Transition
3 then State3[]=State2[]* Transition
...and so on

I'm having a problem to iterate the values of resultant matrix using loops:
I don't know how to iterate values via multiplication in python.

Here's my code:

import numpy as np

statevector=np.array([0.2,0.8])

transition=np.array([[0.9,0.1],[0.7,0.3]])

for product in range(0,1):
    product=statevector

    product=np.dot(statevector,transition)

    product=product+1

    r=np.dot(product,transition)
    print(r)

Solution

  • If I understand you correctly, you want to repeatedly multiply the statevector with the transition matrix. One way to do this is in a for loop like this:

    import numpy as np
    
    statevector=np.array([0.2,0.8])
    
    transition=np.array([[0.9,0.1],[0.7,0.3]])
    
    states = [statevector]
    
    for i in range(10):
        statevector=np.dot(statevector,transition)
        states.append(statevector)
    
    print(states)
    

    Every iteration I'm adding the new state to the list states. The end result is:

    [array([0.2, 0.8]), array([0.74, 0.26]), array([0.848, 0.152]), array([0.8696, 0.1304]), array([0.87392, 0.12608]), array([0.874784, 0.125216]), array([0.8749568, 0.1250432]), array([0.87499136, 0.12500864]), array([0.87499827, 0.12500173]), array([0.87499965, 0.12500035]), array([0.87499993, 0.12500007])]