Convert vector into diagonal matrix

$\begingroup$

Given a vector $[x_1,x_2,x_3, \dots, x_n]^T$, is it possible to obtain a diagonal matrix,

$ \left[\begin{array}{c c c c c} x_1 & 0 & 0 & \dots & 0\\ 0 & x_2 & 0 & \dots & 0\\ 0 & 0 & x_3 & \dots & 0\\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \dots & x_n\\ \end{array} \right] $

using matrix operations (like multiplication and/or addition with identity matrix etc)? This seems trivial, but I am unable to work it out!

I need to do this for automation of process in Maxima, so that I don't have to manually type in the elements diagonally. Thanks.

$\endgroup$ 2

5 Answers

$\begingroup$

$$\operatorname{diag} (\mathbf{x}) = \sum_{i=1}^n\mathbf{e}_i'\mathbf{x}\mathbf{e}_i\mathbf{e}_i'$$

Where $\mathbf{e}_i$ is the i-th basis vector of $\mathbb{R}^n$ and $'$ denotes the transpose.

$\endgroup$ 5 $\begingroup$

I thought about this, and the best I can come up with is the following. It's about as fast as the standard matlab diag() function on small matrices, but I wasn't particularly rigorous. Anyway:

$$ v = v_i \in \mathbb{R}^n \\ D = diag(v) = D_{ii} \in \mathbb{R}^{n \times n} \\ D = \textbf{I}_n \cdot \left( \textbf{1}_n^T \otimes v \right) $$

In Matlab, this can be written as follows:

>> v = sym('v',[5 1])
D = eye(length(v)) .* kron( ones(length(v),1)',v )
v = v1 v2 v3 v4 v5
D =
[ v1, 0, 0, 0, 0]
[ 0, v2, 0, 0, 0]
[ 0, 0, v3, 0, 0]
[ 0, 0, 0, v4, 0]
[ 0, 0, 0, 0, v5]
$\endgroup$ 2 $\begingroup$

I cannot replicate @Ronen's code in python. Instead, I just use the outer product:

import numpy as np
np.identity(len(x)) * np.outer(np.ones(len(x)), x)

where * is element by element multiplication

$\endgroup$ 1 $\begingroup$

Given a vector x, and you would like to build the diagonal matrix from it: Another mathematical operation could be the so called "hadamard product". It does basically element-wise multiplication of all elements. On order to do so, you need first to build a matrix out of the vector x. That is, use the outer product with another vector which contains only 1 entries: x * [1,1,1,1,1] = tempMatrix

Now apply the hadamard multiplication to this tempMatrix with the identity matrix

Most CAS packages like matlab, mathematica, and probably maxima aswell, offer an operator for the hadamard product In Matlab you would write: eye(5) .* (x * ones(1,5)) or simply diag(x), which does the same.

In maxima you would write ident(5) * (x.[1,1,1,1,1])

$\endgroup$ 1 $\begingroup$

In Maxima, if you define the vector as a list (i.e. x: [x1,x2,x3,..,xn]) you obtain the diagonal matrix with

ident(n)*x

or, even better, with (thanks to Sourabh Bhat for pointing out)

diag_matrix(x1,x2,...,xn)
$\endgroup$ 1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like