如何将Numpy数组提升为幂? (对应于重复的矩阵乘法,而不是元素) [英] How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)
问题描述
我想将二维numpy array
提升为某个数字n
的幂,让我们称之为A
,但是到目前为止,我一直未能找到实现该功能的函数或运算符.
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.
我知道我可以将其转换为matrix
类型,并使用这样的事实:(与Matlab中的行为类似),A**n
可以满足我的要求(对于array
相同的表达式表示按元素取幂).但是,强制转换为matrix
并返回似乎是一个非常丑陋的解决方法.
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 ugly workaround though.
当然必须有一种很好的方法来执行该计算,同时将格式保持为array
?
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
作为一个简单的例子:
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)
这将产生:
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]])
这篇关于如何将Numpy数组提升为幂? (对应于重复的矩阵乘法,而不是元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!