'is there a way to reduce reduce the number of for loops and use numpy functions to reduce time for code completion

Passing a function with parameters arr(array), risk_matrix(square matrix),risk_factor(float value)

def infection(arr,risk_matrix,risk_factor):
    arr=arr*risk_factor
    tup=np.linalg.eig(arr)
    evalue=tup[0]
    evector=tup[1]
    for i in range (len(arr)):
        for j in range (i,len(arr)):
            if i==j:
                continue
            risk_edge=0
            for k in range (len(evalue)):
                risk_edge=risk_edge+(math.exp(evalue[k])*evector[i][k]*evector[j][k])
            risk_matrix[i][j]=risk_edge
            risk_matrix[j][i]=risk_edge
    return risk_matrix

evalue is nx1 array and evector in nxn array



Solution 1:[1]

used array broadcasting, speed is improved. if there is a even better method let me know

def infection(arr,risk_matrix,risk_factor):
    arr=arr*risk_factor
    tup=np.linalg.eig(arr)
    evalue=tup[0]
    evector=tup[1]
    for i in range (len(arr)):
        for j in range (i+1,len(arr)):
            risk_edge=(np.exp(evalue)*evector[i]*evector[j]).sum()
            risk_matrix[i][j]=risk_edge
            risk_matrix[j][i]=risk_edge
    return risk_matrix

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PyroSama