# Is there a faster way to vectorize a matrix than this?

I want to put all the columns stacked up, as a vector.

The fastest code I could come up with was

Transpose[{Flatten[Transpose[A]]}]


Is there a faster way?

• This is about 30% to 40% faster for matrices of shape 1000x1000: ArrayReshape[Transpose[A], {Times @@ Dimensions[A], 1}] – wilsnunn Nov 5 '18 at 10:48
• And seems to be up to 50% faster in other instances! – wilsnunn Nov 5 '18 at 10:57
• Is keeping the extra dimension beneficial? – Αλέξανδρος Ζεγγ Nov 5 '18 at 11:02

Note that here you are wasting a lot of time by transposing twice (this is the slowest operation here). See the breakdown of timings of your code here:

    A = ArrayReshape[Range[1000^2], {1000, 1000}];

RepeatedTiming[transposeA = Transpose[A];]

(* {0.0034, Null} *)

RepeatedTiming[flattenA = Flatten[transposeA];]

(* {0.00275, Null} *)

RepeatedTiming[Transpose[{flattenA}];]

(* {0.00555, Null}

If instead we use (as I suggested in the comment above) ArrayReshape[Transpose[A], {Times @@ Dimensions[A], 1}] then the timings are a lot more favourable: *)

RepeatedTiming[transposeA = Transpose[A];]


{0.0034, Null}

RepeatedTiming[dimA = Times @@ Dimensions[A];]


{2.04*10^-6, Null}

RepeatedTiming[ArrayReshape[transposeA, {dimA,1}];]


{0.00263, Null}

These result in the following differences:

RepeatedTiming[Transpose[{Flatten[Transpose[A]]}];]


{0.0122, Null}

RepeatedTiming[ArrayReshape[Transpose[A], {Times @@ Dimensions[A], 1}];]


{0.0032, Null}

In this case, the new code is nearly 4 times faster.