ArrayPad unexpected changing of order
A way without ArrayPad
Join[{y, z}, Map[x &, Range[4]]]
(* Out: {y, z, x, x, x, x} *)
PadRight[{y, z}, 10, x]
First a function that gives the desired output:
ClearAll[arrayPad]
arrayPad = ArrayPad[#, {{0, 0}, {#3, 0}}, PadRight[#2, #3 + Length@#[[1]], #2]] &;
Examples:
Row[{Grid[Prepend[{#, {y, z}, 2,
arrayPad[#, {y, z}, 2]} & /@ ({ ConstantArray[x, #]} & /@ Range[4]),
{"a", "padding", "m", "arrayPad[a,padding,m]"}], Dividers -> All],
Grid[Prepend[{#, {y, z, w}, 3,
arrayPad[#, {y, z, w}, 3]} & /@ ({ ConstantArray[x, #]} & /@ Range[4]),
{"a", "padding", "m", "arrayPad[a,padding,m]"}], Dividers -> All],
Grid[Prepend[{#, Range[4], 5,
arrayPad[#, Range[4], 5]} & /@ ({ ConstantArray[x, #]} & /@ Range[4]),
{"a", "padding", "m", "arrayPad[a,padding,m]"}], Dividers -> All]}, Spacer[5]]
How come ArrayPad changes the ordering?
Trace @ ArrayPad[{{x}}, {{0, 0} , {2, 0}}, {y, z}]
{ArrayPad[{{x}}, {{0, 0}, {2, 0}}, {y, z}], PadLeft[{{x}}, {1, 3}, {y, z}, {0, 0}], {{z, y, x}}}
PadLeft >> Details
That is, ArrayPad[{a}, {{0,0}, {m,0}}, padding]
behaves as if it takes PadLeft[padding, m + Length[a], padding]
and replaces the last Length[a]
elements of this list with a
. For the example in OP:
PadLeft[{y, z}, 2 + #, {y, z}] & /@ Range[3]
{ {z, y, z}, {y, z, y, z}, {z, y, z, y, z}}
whereas
PadRight[{y, z}, 2 + #, {y, z}] & /@ Range[3]
{{y, z, y}, {y, z, y, z}, {y, z, y, z, y}}
In other words, ArrayPad[a, {{0,0}, {m,0}}, padding]
behaves like the version of arrayPad
above with PadRight
replaced with PadLeft
:
padding = Range[5];
pl = RandomInteger[{1, 10}];
And @@ (ArrayPad[{ConstantArray[x, #]}, {{0, 0}, {pl, 0}}, padding] ===
ArrayPad[{ConstantArray[x, #]}, {{0, 0}, {pl, 0}},
PadLeft[padding, pl + #, padding]] & /@ Range[10])
True