Back to Problems
## Convert Vector to Diagonal Matrix

#### Example

## Understanding Diagonal Matrices

Write a Python function to convert a 1D numpy array into a diagonal matrix. The function should take in a 1D numpy array x and return a 2D numpy array representing the diagonal matrix.

Example: x = np.array([1, 2, 3]) output = make_diagonal(x) print(output) # Output: # [[1. 0. 0.] # [0. 2. 0.] # [0. 0. 3.]] Reasoning: The input vector [1, 2, 3] is converted into a diagonal matrix where the elements of the vector form the diagonal of the matrix.

A diagonal matrix is a square matrix in which the entries outside the main diagonal are all zero. The main diagonal is the set of entries extending from the top left to the bottom right of the matrix.

In this problem, you will write a function to convert a 1D numpy array (vector) into a diagonal matrix. The resulting matrix will have the elements of the input vector on its main diagonal, and zeros elsewhere.

Given a vector \( \mathbf{x} = [x_1, x_2, \ldots, x_n] \), the corresponding diagonal matrix \( \mathbf{D} \) is:

\[ \mathbf{D} = \begin{bmatrix} x_1 & 0 & 0 & \cdots & 0 \\ 0 & x_2 & 0 & \cdots & 0 \\ 0 & 0 & x_3 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & x_n \end{bmatrix} \]Diagonal matrices are important in various mathematical and scientific computations because of their simple structure and properties.

import numpy as np def make_diagonal(x): identity_matrix = np.identity(np.size(x)) return (identity_matrix*x)

Output will be shown here.

Solution copied to clipboard!