← back

Convert Vector to Diagonal Matrix

#35 · Linear Algebra · Easy

⊣ Solve on deep-ml.com

Problem

Convert a 1D vector into a diagonal matrix. Given a list or 1D array of values, return a 2D square matrix with those values on the main diagonal and zeros elsewhere.

Solution

1
2
3
4
5
6
7
8
import numpy as np

def make_diagonal(vector):
    n = len(vector)
    matrix = np.zeros((n, n))
    for i in range(n):
        matrix[i][i] = vector[i]
    return matrix.tolist()

Explanation

  1. Determine the length n of the input vector.
  2. Create an n x n zero matrix.
  3. Set each diagonal element matrix[i][i] to the corresponding vector value.
  4. Return as a list of lists.

Complexity

  • Time: O(n) for setting diagonal elements
  • Space: O(n^2) for the output matrix