Loading content...
A diagonal matrix is a special square matrix where all elements outside the main diagonal are zero. Diagonal matrices are fundamental structures in linear algebra with important properties that make them computationally efficient for many operations.
Given a one-dimensional vector x of length n, your task is to construct an n × n diagonal matrix D where each element x[i] from the input vector is placed at position (i, i) on the main diagonal, and all other positions contain zeros.
Mathematically, the diagonal matrix D is defined as:
$$D_{ij} = \begin{cases} x_i & \text{if } i = j \ 0 & \text{otherwise} \end{cases}$$
Properties of Diagonal Matrices:
Your Task: Write a Python function that takes a 1D NumPy array (or list) and returns a 2D NumPy array representing the corresponding diagonal matrix. The output matrix should be of type float.
x = [1.0, 2.0, 3.0][[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]]Explanation
The input vector has 3 elements, so we create a 3×3 matrix. • Position (0,0): 1.0 (first element of the vector) • Position (1,1): 2.0 (second element of the vector) • Position (2,2): 3.0 (third element of the vector) • All other positions: 0.0 The resulting diagonal matrix has the vector elements along its main diagonal.
x = [5.0, 10.0][[5.0, 0.0], [0.0, 10.0]]Explanation
With a 2-element vector, we construct a 2×2 diagonal matrix. • Position (0,0): 5.0 • Position (1,1): 10.0 • Off-diagonal elements: 0.0 This is a simple scaling matrix that would scale the x-component by 5 and the y-component by 10 when used in a linear transformation.
x = [1.0, -2.0, 3.5, -4.5][[1.0, 0.0, 0.0, 0.0], [0.0, -2.0, 0.0, 0.0], [0.0, 0.0, 3.5, 0.0], [0.0, 0.0, 0.0, -4.5]]Explanation
A 4-element vector produces a 4×4 diagonal matrix. Notice that the vector can contain: • Positive values (1.0, 3.5) • Negative values (-2.0, -4.5) • Decimals/floating-point numbers All these values are correctly placed on the main diagonal, with zeros filling all 12 off-diagonal positions in this 4×4 matrix.
Constraints