开发者

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

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 function or operator to do that.

I'm aware that I could cast it to the matrix type and use the fact that then (similar to what would be the behaviour in Matlab), A**n does just what I want, (for array the same expression means elementwise exponentiation). Casting to matrix and back seems like a rather 开发者_C百科ugly workaround though.

Surely there must be a good way to perform that calculation while keeping the format to array?


I believe you want numpy.linalg.matrix_power

As a quick example:

import numpy as np
x = np.arange(9).reshape(3,3)
y = np.matrix(x)

a = y**3
b = np.linalg.matrix_power(x, 3)

print a
print b
assert np.all(a==b)

This yields:

In [19]: a
Out[19]: 
matrix([[ 180,  234,  288],
        [ 558,  720,  882],
        [ 936, 1206, 1476]])

In [20]: b
Out[20]: 
array([[ 180,  234,  288],
       [ 558,  720,  882],
       [ 936, 1206, 1476]])


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   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜