如何将Numpy数组提升为幂? (对应于重复的矩阵乘法,而不是元素) [英] How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)

查看:149
本文介绍了如何将Numpy数组提升为幂? (对应于重复的矩阵乘法,而不是元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将二维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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆