Problems
Loading...
1 / 1

Make Diagonal Matrix

Linear Algebra
Easy

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,if i=j,0,if ij,D_{ij} = \begin{cases} v_i, & \text{if } i = j, \\ 0, & \text{if } i \ne j, \end{cases}

where v=[v0,v1,…,vn−1] and D is an n×n matrix.

Function Arguments

  • v: 1D array-like, shape (n,) - diagonal values
Loading visualization...

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