8
$\begingroup$

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?

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

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.

$\endgroup$

Your Answer

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

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