Matrix Power With np.linalg.matrix_power
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `mat_power(A, n)` that returns the square matrix `A` raised to the integer power `n` using true matrix multiplication (not elementwise). Delegate to `np.linalg.matrix_power` and mirror its edge-case behavior.
The function must:
- For `n > 0`, return the repeated product `A @ A @ ... @ A`.
- For `n == 0`, return the identity matrix of matching shape.
- For `n < 0`, return the inverse of `A` raised to `abs(n)`, raising an error if `A` is singular.
For example:
```python
A = np.array([[2, 0], [0, 3]])
mat_power(A, 2) # [[4, 0], [0, 9]]
mat_power(A, 0) # [[1, 0], [0, 1]]
mat_power(A, -1) # [[0.5, 0.], [0., 0.33333333]]
```
```hint Test matrix
The example matrix is diagonal, which hides some mistakes. Try your function on a non-diagonal matrix such as `[[1, 1], [0, 1]]` too.
```
### Constraints & Assumptions
- `A` is a square 2-D array (d x d).
- `n` is a Python or NumPy integer and can be negative, zero or positive.
### What a Strong Answer Covers
- How a matrix power differs from the elementwise `**` operator.
- The result for each sign of `n`, including its dtype.
- How many matrix multiplications the computation needs and the total cost for a d x d matrix.
- What happens for a singular `A` with a negative exponent, and for a non-integer exponent.
### Follow-up Questions
- How does `matrix_power` avoid `n` multiplications for large exponents?
- What happens for negative `n` when `A` is singular?
- How would you compute a non-integer power of a matrix, such as its square root?
Overview: Write a NumPy function that raises a square matrix to an integer power with np.linalg.matrix_power, covering positive, zero and negative exponents. It tests matrix versus elementwise powers, exponentiation by squaring, the output dtype and the behavior for singular matrices.