Sub-Diagonal Matrix With np.diag
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given an integer `n`, return an `n x n` float array of zeros except the sub-diagonal (offset `-1`), which holds `1, 2, ..., n-1`.
Requirements:
- Shape `(n, n)`, float dtype.
- `1, 2, ..., n-1` at offset `-1`, all other entries `0`.
- Construct it with `np.diag(values, k=-1)`.
For example, with `n = 4` the function returns:
```python
[[0., 0., 0., 0.],
[1., 0., 0., 0.],
[0., 2., 0., 0.],
[0., 0., 3., 0.]]
```
```hint Output size
When `np.diag` gets a 1-D array, the size of the square matrix it returns depends on both the array's length and `k`. Work out which length gives exactly `n x n`, and check which dtype the result inherits.
```
### Constraints & Assumptions
- `n >= 1`. For `n = 1`, return a `1 x 1` zero array.
- The result must be a float array (`float64` is fine).
### What a Strong Answer Covers
- How `np.diag` behaves when its input is 1-D, and what a negative `k` means.
- Why the values array has length `n-1` and how that sets the output shape.
- How the result ends up with a float dtype.
- The `n = 1` case, where the values array is empty.
### Follow-up Questions
- How would you place the same values on the super-diagonal instead?
- How could you build this without `np.diag`?
- How would you read the sub-diagonal back out of an existing `n x n` matrix?
Overview: Build an n by n NumPy float array that is zero everywhere except the sub-diagonal, which holds the values 1 through n-1. The question tests how np.diag constructs a matrix from a 1-D array, how the offset k sets both position and size, and how the dtype and the n = 1 case are handled.