How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)
45,840
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]])
Related videos on Youtube
Author by
mirari
Updated on July 09, 2022Comments
-
mirari almost 2 years
I want to raise a 2-dimensional numpy
array
, let's call itA
, to the power of some numbern
, 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, (forarray
the same expression means elementwise exponentiation). Casting tomatrix
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
?-
dr jimbob about 13 yearsWhile its possible as Joe Kingston pointed out, note that arrays and matrices are fundamentally different. An
array
is a numerical collection of elements in multi-dimensions, where amatrix
is an abstract object (represented by an 2-d array)-- the same difference as between a vector and a 1-d array. (It makes sense for an inventory of fruit to be a array of [1,2,3] representing 1 apple, 2 oranges, 3 bananas but no sense for an vector -- apples can't add/multiple/transform into oranges). Thus arrays have element-by-element operations and matrices have matrix multiplications, det(), etc. -
Sven Marnach about 13 yearsIf you like Joe's answer, you should check it as "accepted", to give credit to Joe and to let others know this question is dealt with.
-
-
mirari about 13 yearsYes, that is exactly what I needed. Thank you!
-
mirari about 13 yearsI feel somewhat sheepish for not having thought to look explicitly in the
linalg
module, but particular thanks for pointing out that that's the place as well. Nice quick example; very illustrative. -
Emmanuel Murairi about 2 yearsthe pow function raises each value on the matrix by power n which is different from matrix power which raises the matrix by power n (multiply the matrix by itself n times)