Raise a square matrix to the (integer) power `n`. 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. If ``n < 0``, the inverse is computed and then rais
(a, n)
| 666 | |
| 667 | @array_function_dispatch(_matrix_power_dispatcher) |
| 668 | def matrix_power(a, n): |
| 669 | """ |
| 670 | Raise a square matrix to the (integer) power `n`. |
| 671 | |
| 672 | For positive integers `n`, the power is computed by repeated matrix |
| 673 | squarings and matrix multiplications. If ``n == 0``, the identity matrix |
| 674 | of the same shape as M is returned. If ``n < 0``, the inverse |
| 675 | is computed and then raised to the ``abs(n)``. |
| 676 | |
| 677 | .. note:: Stacks of object matrices are not currently supported. |
| 678 | |
| 679 | Parameters |
| 680 | ---------- |
| 681 | a : (..., M, M) array_like |
| 682 | Matrix to be "powered". |
| 683 | n : int |
| 684 | The exponent can be any integer or long integer, positive, |
| 685 | negative, or zero. |
| 686 | |
| 687 | Returns |
| 688 | ------- |
| 689 | a**n : (..., M, M) ndarray or matrix object |
| 690 | The return value is the same shape and type as `M`; |
| 691 | if the exponent is positive or zero then the type of the |
| 692 | elements is the same as those of `M`. If the exponent is |
| 693 | negative the elements are floating-point. |
| 694 | |
| 695 | Raises |
| 696 | ------ |
| 697 | LinAlgError |
| 698 | For matrices that are not square or that (for negative powers) cannot |
| 699 | be inverted numerically. |
| 700 | |
| 701 | Examples |
| 702 | -------- |
| 703 | >>> import numpy as np |
| 704 | >>> from numpy.linalg import matrix_power |
| 705 | >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit |
| 706 | >>> matrix_power(i, 3) # should = -i |
| 707 | array([[ 0, -1], |
| 708 | [ 1, 0]]) |
| 709 | >>> matrix_power(i, 0) |
| 710 | array([[1, 0], |
| 711 | [0, 1]]) |
| 712 | >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements |
| 713 | array([[ 0., 1.], |
| 714 | [-1., 0.]]) |
| 715 | |
| 716 | Somewhat more sophisticated example |
| 717 | |
| 718 | >>> q = np.zeros((4, 4)) |
| 719 | >>> q[0:2, 0:2] = -i |
| 720 | >>> q[2:4, 2:4] = i |
| 721 | >>> q # one of the three quaternion units not equal to 1 |
| 722 | array([[ 0., -1., 0., 0.], |
| 723 | [ 1., 0., 0., 0.], |
| 724 | [ 0., 0., 0., 1.], |
| 725 | [ 0., 0., -1., 0.]]) |
searching dependent graphs…