3

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} $$

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
stollenm
  • 141
  • 4
  • 2
    vector and matrix are vague terms in Mathematica so please add input and expected output in terms of Mathematica code in order to make the question clear. – Kuba Feb 16 '17 at 10:31
  • Thanks for the Accept. Please see the additional example of Flatten that I added afterward. – Mr.Wizard Feb 16 '17 at 13:59

3 Answers3

7

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:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • Unless OP sees column vector as: List /@ {a[1, 1], a[2, 1], a[1, 2], a[2, 2]} – Kuba Feb 16 '17 at 13:34
  • @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... – Mr.Wizard Feb 16 '17 at 13:37
4
{{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[].

zhk
  • 11,939
  • 1
  • 22
  • 38
1

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
cyrille.piatecki
  • 4,582
  • 13
  • 26