I want to do padding of matrix

a = {{x,x},{x,u}};


to

b = {{x, x, x}, {x, u, u}, {x, x, x}}

c = {{x, x, x, x}, {x, u, u, u}, {x, x, x, x}, {x, x, x, x}}


and soon...

How I can automatically do this?

• You can use ArrayFlatten. Commented Mar 16, 2014 at 22:39
• Do all subsequent elements have only THREE rows? Commented Mar 16, 2014 at 22:58
• Isn't it very similar to your other question? mathematica.stackexchange.com/q/43071/193 Commented Mar 16, 2014 at 23:00
• @Kuba In fact the OP added a third element showing that the result should always be a square matrix. He hasn't be very outspoken, though. The problem I find with this question is that the OP already asked one of these (where your answer is quite good) but isn't trying with the hints given there (ArrayPad, etc) Commented Mar 18, 2014 at 16:42
• @belisarius If you are ok with that then I should be too :P Yes, that's often a problem, their loss if they don't want to understand the code :|
– Kuba
Commented Mar 18, 2014 at 16:49

I must confess to being confused about the ultimate aim. I, therefore, am sorry if these speculations miss the mark.

If the aim is to progressively pad right with the last element of every list then:

g[s_, n_] := PadRight[#, n, Last@#] & /@ s


Repeatedly applying:

Column[Table[g[a, j], {j, 3, 6}]]


yields:

If the intent is to sequential pad right with the first element then pad right with the last element of each subset then:

f[s_] := With[{w = First[s]},


You can get lists:

FoldList[g[f[#1], #2] &, a, Range[3, 6]]


If the aim is just to expand first list then apply g:

Table[g[f[a], j], {j, 3, 6}]


The latter seems to be consistent with outcome presented. However, I may have misunderstood intent.

• how to write only this out of full fold list: {{x, x, x, x}, {x, u, u, u}, {x, x, x, x}, {x, x, x, x}} Commented Mar 17, 2014 at 23:00
• Thanks...I want this....FoldList[g[f[#1], #2] &, a, Range[3, 6]][[n]] // MatrixForm, n=1,2,3... Commented Mar 17, 2014 at 23:04

You might use:

a = {{x, x}, {x, u}};

{#, #2, #} & @@ ArrayPad[a, {0, {0, 3}}, "Fixed"]

{{x, x, x, x, x}, {x, u, u, u, u}, {x, x, x, x, x}}

• LOL - this was flagged as a "low quality post" - I guess the clever filter is broken.
– ciao
Commented Mar 17, 2014 at 2:06
• @Mr.Wizard thank you again for educating...ArrayPad. I am still uncertain about ultimate aim. Commented Mar 17, 2014 at 3:58
base = {{x, x}, {x, u}, {x, x}}

pads = Rest@NestList[Function[arg, PadRight[#, Length@# + 1, Last@#] & /@ arg],base, 4];


Each entry of pads is one more level of padding.

Change the 4 in the NestList to however many different levels of padding you want produced.

Perhaps a bit "cleaner", same results:

Rest@NestList[ArrayPad[#, {{0, 0}, {0, 1}}, "Fixed"] &, base, 4]