3
$\begingroup$

Why does ArrayPad[Range[7], 4, Padding -> {1, 2, 3}] return {2, 3, 1, 2, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1}?

I expect it to return {3, 1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 1}, what am I missing?

$\endgroup$
  • 3
    $\begingroup$ The details on how padding is performed are explained in the docs for PadLeft[] and PadRight[]. ArrayPad[] behaves consistently with these two. For more clarity, compare PadLeft[Range[7], 11, {1, 2, 3}] and PadLeft[{}, 11, {1, 2, 3}] (and analogously for PadRight[]). $\endgroup$ – J. M.'s technical difficulties Nov 14 '19 at 7:28
  • $\begingroup$ I found in documentation: "With padding {Subscript[x, 1],Subscript[x, 2],[Ellipsis],Subscript[x, s]}, cyclic repetitions of the Subscript[x, i] are effectively laid down and then the list is superimposed on top of them, with the last element of the list lying on an occurrence of Subscript[x, s]." That's so unobvious and inconvinient I feel! $\endgroup$ – Markhaim Nov 14 '19 at 9:13
  • $\begingroup$ Related: (72740) $\endgroup$ – Mr.Wizard Jun 5 at 8:37
3
$\begingroup$

Instead of prepending the elements cyclically (which would give the intuitive {3, 1, 2, 3, 1, 2, 3, 4, 5, 6, 7}, PadLeft (and thus Arraypad) effectively does

Block[
  {cyc = PadLeft[{}, 11, {1, 2, 3}] (*cyclic repetitions laid down*)},
  cyc[[-7 ;;]] = Range[7] (*list is superimposed on top of them*);
  cyc
]
PadLeft[Range[7], 11, {1, 2, 3}] == %

{2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3}

True

as described in the documentation

With padding $\left\{x_1,x_2,\ldots ,x_s\right\}$, cyclic repetitions of the $x_i$ are effectively laid down and then the list is superimposed on top of them, with the last element of the list lying on an occurrence of $x_s$.

Or more in general

myPadLeft[list_, n_, padding_] := Block[
  {cyc = PadLeft[{}, n, padding]},
  cyc[[-Length@list ;;]] = list;
  cyc
]

And another way of thinking about it

myPadLeft2[list_, n_, padding_] := PadLeft[{}, n, padding][[;; -Length@list - 1]]~Join~list
| improve this answer | |
$\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.