Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ugly workaround though.

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

like image 331
mirari Avatar asked Feb 16 '11 15:02

mirari


People also ask

How do you raise a matrix to a power NumPy?

The numpy. linalg. matrix_power() method is used to raise a square matrix to the power n. It will take two parameters, The 1st parameter is an input matrix that is created using a NumPy array and the 2nd parameter is the exponent n, which refers to the power that can be zero or non-zero integers.

How do you raise a matrix power in Python?

To raise a square matrix to the power n in Linear Algebra, use the numpy. linalg. matrix_power() in Python For positive integers n, the power is computed by repeated matrix squarings and matrix multiplications. If n == 0, the identity matrix of the same shape as M is returned.

How do you perform matrix multiplication on the NumPy arrays?

To multiply two matrices use the dot() function of NumPy. It takes only 2 arguments and returns the product of two matrices.


1 Answers

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]]) 
like image 142
Joe Kington Avatar answered Oct 14 '22 02:10

Joe Kington