2
$\begingroup$

As the titel says I want to transpose a matrix containing rows of unequal length, to be able to transport them to excel (in row form, there are too many datapoint to write them in a cell. In another topic if found to use flatten : Transpose uneven lists

However, this does not give me the right result:

Example:

list = {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3, 4,5}, {1, 2, 3, 4, 5}};
Flatten[list, {{2},{1}}]

Results into:

{{1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2}, {3, 3, 3, 3, 3, 3}, {4, 4, 4, 4}, {5, 5}}

But the result I want is:

{{1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2}, {3, 3, 3, 3, 3, 3}, {4, 4,"" , "" , 4, 4}{,"" , "" , "" , "" , 5, 5}}

So I want to keep the rows together as they are, but only print them into columns. Is this possible?

$\endgroup$
  • 3
    $\begingroup$ What is the "rule" that puts the 4 in pairs front and back, yet the 5 is only at the back? $\endgroup$ – ciao Feb 24 '14 at 11:10
7
$\begingroup$

Is this what you want?

list = {{1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3},
        {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}};

Transpose@PadRight[list, Automatic, ""]

{{1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2}, {3, 3, 3, 3, 3, 3},
 {4, 4, "", "", 4, 4}, {"", "", "", "", 5, 5}}
$\endgroup$
  • $\begingroup$ your answer is most compact...always learning Automatic...got my vote despite nose in front in a three horse race $\endgroup$ – ubpdqn Feb 24 '14 at 11:59
4
$\begingroup$

If the aim is for export into spreadsheet you could use:

With[{m = Max[Length /@ list]},Transpose@(PadRight[#, m, ""] & /@ list)]

Visualizing result to see if this is your aim:

enter image description here

$\endgroup$
  • 2
    $\begingroup$ And the photo finish.... @ubpdqn! Or so it showed up on my screen. :P $\endgroup$ – Michael E2 Feb 24 '14 at 11:15
  • $\begingroup$ @MichaelE2 lol! now if only it answers OP's question $\endgroup$ – ubpdqn Feb 24 '14 at 11:17
  • $\begingroup$ Great! All three results do what I want! $\endgroup$ – Wiebe Feb 24 '14 at 11:53
3
$\begingroup$
maxLen = Max@(Length /@ list)

Transpose[PadRight[#, maxLen, ""] & /@ list]
$\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.