How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)

前端 未结 2 1507
無奈伤痛
無奈伤痛 2021-02-04 03:29

I want to raise a 2-dimensional numpy array, let\'s call it A, to the power of some number n, but I have thus far failed to find the funct

2条回答
  •  自闭症患者
    2021-02-04 03:59

    The opencv function cvPow seems to be about 3-4 times faster on my computer when raising to a rational number. Here is a sample function (you need to have the pyopencv module installed):

    import pyopencv as pycv
    import numpy
    def pycv_power(arr, exponent):
        """Raise the elements of a floating point matrix to a power. 
        It is 3-4 times faster than numpy's built-in power function/operator."""
        if arr.dtype not in [numpy.float32, numpy.float64]:
            arr = arr.astype('f')
        res = numpy.empty_like(arr)
        if arr.flags['C_CONTIGUOUS'] == False:
            arr = numpy.ascontiguousarray(arr)        
        pycv.pow(pycv.asMat(arr), float(exponent), pycv.asMat(res))
        return res   
    

提交回复
热议问题