Make Diagonal Matrix
Make Diagonal Matrix
Given a 1D vector v of length n, build an n×n diagonal matrix with v on its main diagonal and zeros elsewhere.
Mathematical Definition
Diagonal Matrix:
Dij={vi,0,if i=j,if i=j,where v=[v0,v1,…,vn−1] and D is an n×n matrix.
Function Arguments
v: 1D array-like, shape (n,)- diagonal values
Examples
Input: v = [3, 5]
Output: shape = (2, 2), diagonal = [3, 5]
Input: v = [1.5]
Output: shape = (1, 1), diagonal = [1.5]
Input: v = [0, 0, 2]
Output: shape = (3, 3), diagonal = [0, 0, 2]
Hint 1
Create a zero matrix using np.zeros(), then fill the diagonal with a loop.
Hint 2
Alternatively, use np.diag() directly for a one-liner solution.
Requirements
- Return (n, n) NumPy array with v on main diagonal
- All off-diagonal elements are zero
- Preserve float type if present
- Handle n=1 correctly
Constraints
- 1 ≤ n ≤ 10,000
- NumPy only
- Time limit: 200ms
Try Similar Problems
Log in to take notes on this problem
Accepts: array
Make Diagonal Matrix
Make Diagonal Matrix
Given a 1D vector v of length n, build an n×n diagonal matrix with v on its main diagonal and zeros elsewhere.
Mathematical Definition
Diagonal Matrix:
Dij={vi,0,if i=j,if i=j,where v=[v0,v1,…,vn−1] and D is an n×n matrix.
Function Arguments
v: 1D array-like, shape (n,)- diagonal values
Examples
Input: v = [3, 5]
Output: shape = (2, 2), diagonal = [3, 5]
Input: v = [1.5]
Output: shape = (1, 1), diagonal = [1.5]
Input: v = [0, 0, 2]
Output: shape = (3, 3), diagonal = [0, 0, 2]
Hint 1
Create a zero matrix using np.zeros(), then fill the diagonal with a loop.
Hint 2
Alternatively, use np.diag() directly for a one-liner solution.
Requirements
- Return (n, n) NumPy array with v on main diagonal
- All off-diagonal elements are zero
- Preserve float type if present
- Handle n=1 correctly
Constraints
- 1 ≤ n ≤ 10,000
- NumPy only
- Time limit: 200ms
Try Similar Problems
Log in to take notes on this problem
Accepts: array