MCPcopy Create free account
hub / github.com/numpy/numpy / matrix_power

Function matrix_power

numpy/linalg/linalg.py:570–682  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

568
569@array_function_dispatch(_matrix_power_dispatcher)
570def matrix_power(a, n):
571 """
572 Raise a square matrix to the (integer) power `n`.
573
574 For positive integers `n`, the power is computed by repeated matrix
575 squarings and matrix multiplications. If ``n == 0``, the identity matrix
576 of the same shape as M is returned. If ``n < 0``, the inverse
577 is computed and then raised to the ``abs(n)``.
578
579 .. note:: Stacks of object matrices are not currently supported.
580
581 Parameters
582 ----------
583 a : (..., M, M) array_like
584 Matrix to be "powered".
585 n : int
586 The exponent can be any integer or long integer, positive,
587 negative, or zero.
588
589 Returns
590 -------
591 a**n : (..., M, M) ndarray or matrix object
592 The return value is the same shape and type as `M`;
593 if the exponent is positive or zero then the type of the
594 elements is the same as those of `M`. If the exponent is
595 negative the elements are floating-point.
596
597 Raises
598 ------
599 LinAlgError
600 For matrices that are not square or that (for negative powers) cannot
601 be inverted numerically.
602
603 Examples
604 --------
605 >>> from numpy.linalg import matrix_power
606 >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
607 >>> matrix_power(i, 3) # should = -i
608 array([[ 0, -1],
609 [ 1, 0]])
610 >>> matrix_power(i, 0)
611 array([[1, 0],
612 [0, 1]])
613 >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
614 array([[ 0., 1.],
615 [-1., 0.]])
616
617 Somewhat more sophisticated example
618
619 >>> q = np.zeros((4, 4))
620 >>> q[0:2, 0:2] = -i
621 >>> q[2:4, 2:4] = i
622 >>> q # one of the three quaternion units not equal to 1
623 array([[ 0., -1., 0., 0.],
624 [ 1., 0., 0., 0.],
625 [ 0., 0., 0., 1.],
626 [ 0., 0., -1., 0.]])
627 >>> matrix_power(q, 2) # = -np.eye(4)

Callers 5

__pow__Method · 0.90
test_returntypeMethod · 0.90
test_listMethod · 0.90
test_large_powerMethod · 0.90
tzMethod · 0.90

Calls 8

asanyarrayFunction · 0.90
empty_likeFunction · 0.90
eyeFunction · 0.90
_assert_stacked_2dFunction · 0.85
_assert_stacked_squareFunction · 0.85
absFunction · 0.85
invFunction · 0.70
indexMethod · 0.45

Tested by 4

test_returntypeMethod · 0.72
test_listMethod · 0.72
test_large_powerMethod · 0.72
tzMethod · 0.72