Search code examples
pythonmatrixnested-loops

Python Nested Loops to get a subcovariance matrix optimizations


I am trying to optimize a function that returns a subcovariance matrix from the full covariance matrix given the desired memmbers. The full covariance matrix could contains 500+ items and I could be looking at a variable number of members each time but likely 20 or less per call. This gets called 10,000+ times.

My code works but I was wondering how to optimize it.

def subcovar(covar,elements):
    numelements = elements.shape[0]
    subcovar = np.zeros((numelements,numelements))

    for i in range(0,numelements):
        for j in range(0,numelements):
            subcovar[i,j]= covar[elements[i],elements[j]]

    return subcovar

Thanks Paul


Solution

  • Why not use matrix slicing? [offical python docs]

    Here's a SO thread on building a sub-matrix by extracting arbitrary (ie non-sequential) rows and columns Slicing of a numpy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)