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]])
Share:
45,840

Related videos on Youtube

mirari
Author by

mirari

Updated on July 09, 2022

Comments

  • mirari
    mirari almost 2 years

    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?

    • dr jimbob
      dr jimbob about 13 years
      While 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 a matrix 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
      Sven Marnach about 13 years
      If 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
    mirari about 13 years
    Yes, that is exactly what I needed. Thank you!
  • mirari
    mirari about 13 years
    I 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
    Emmanuel Murairi about 2 years
    the 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)