How to apply the $\operatorname{vec}$ operator in Mathematica? For example, how can I transform a $2 \times 2$ matrix into a $1 \times 4$ matrix as follows? $$ \operatorname{vec}\left( \begin{bmatrix} a_{1,1} & a_{1,2} \\ a_{2,1} & a_{2,2} \end{bmatrix} \right) = \begin{bmatrix} a_{1,1} \\ a_{2,1} \\ a_{1,2} \\ a_{2,2} \end{bmatrix} $$
3 Answers
Use Flatten
to do this in a single operation.
in = Array[a, {2, 2}]
Flatten[in, {2, 1}]
{{a[1, 1], a[1, 2]}, {a[2, 1], a[2, 2]}} {a[1, 1], a[2, 1], a[1, 2], a[2, 2]}
In Mathematica there are only vectors (lists), not column vectors and row vectors. However if you wish to convert a vector into an array with rows of length one for output the computationally fastest method is typically Partition
:
Partition[{a[1, 1], a[2, 1], a[1, 2], a[2, 2]}, 1]
{{a[1, 1]}, {a[2, 1]}, {a[1, 2]}, {a[2, 2]}}
If that is your goal from the start you can also do that in a single operation using Flatten
:
Flatten[{in}, {3, 2}] (* note the extra {} around in *)
{{a[1, 1]}, {a[2, 1]}, {a[1, 2]}, {a[2, 2]}}
Recommended reading:
-
$\begingroup$ Unless OP sees column vector as:
List /@ {a[1, 1], a[2, 1], a[1, 2], a[2, 2]}
$\endgroup$– Kuba ♦Feb 16, 2017 at 13:34 -
$\begingroup$ @Kuba Good point. There is no such thing as a column vector in Mathematica as you know, but that doesn't mean the OP doesn't potentially want a series of one element rows... $\endgroup$ Feb 16, 2017 at 13:37
{{1, 2}, {4, 5}} // MatrixForm
\begin{bmatrix} 1 & 2 \\ 4 & 5 \end{bmatrix}
ArrayReshape[Transpose[%], {4, 1}] // MatrixForm
\begin{bmatrix} 1 \\ 4\\ 2\\ 5 \end{bmatrix}
Thanks to @cyrille.piatecki for the use of Transpose[]
.
I propose this simple module
vec[mat_] :=
Module[{a = mat},
ArrayReshape[Transpose[
a], {Dimensions[mat][[1]] Dimensions[mat][[2]], 1}]]
apply with
aa = Table[Subscript[a, i, j], {i, 1, 2}, {j, 1, 2}]
this gives the expected result
vec[aa] // MatrixForm
Flatten
that I added afterward. $\endgroup$