3
$\begingroup$

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

$\endgroup$
2
  • 2
    $\begingroup$ 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. $\endgroup$
    – Kuba
    Feb 16, 2017 at 10:31
  • $\begingroup$ Thanks for the Accept. Please see the additional example of Flatten that I added afterward. $\endgroup$
    – Mr.Wizard
    Feb 16, 2017 at 13:59

3 Answers 3

7
$\begingroup$

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:

$\endgroup$
2
  • $\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$
    – Mr.Wizard
    Feb 16, 2017 at 13:37
4
$\begingroup$
{{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[].

$\endgroup$
0
1
$\begingroup$

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
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.