# How to "complete" the table by making all of its rows to have the same number of elements?

Consider the following table:

len = 10^6;
nmax=RandomInteger[{5,6}];
nvals = RandomInteger[{1, nmax}, len];
table = Table[RandomReal[{0, 1}, 2*nvals[[i]]], {i, 1, len, 1}];


Each row is made of 2n elements, where n may vary from 1 to some number nmax. We do not know this nmax a priori and may only extract it by finding the row of table with the maximal number of elements.

Could you please tell me how to complement the rows table with some test elements, say -999, such that each row would have 2nmax elements? I.e., for nmax = 4 and the given row being {1,2,3,4}, it must be converted into {1,2,3,4,-999,-999,-999,-999}.

Also, how to make it packed afterward (as it seems that the complementing procedure will make it unpacked)?

• PadRight[table, {Automatic, 2 nmax}, -999]?
– kglr
Nov 4, 2023 at 14:11
• @kglr : Thanks! However, nmax is unknown a priori, we may extract it only from table. Nov 4, 2023 at 14:13
• @kglr : also, DeveloperPackedArrayQ[table1] returns False, where table1 is the table obtained with the help of your command. It means that any work with it will be much slower than with the packed one. Nov 4, 2023 at 14:16
• PadRight[table, Automatic, -999]
– kglr
Nov 4, 2023 at 14:19

It doesn't matter that nmax is unknown a priori, because PadRight will automatically append -999 up to the length of the longest matrix row. We can see this clearly in the answer of kglr. And equal row lengths are required to pack the array (you cannot pack "ragged" matrices).

len = 10^6;
nmax = RandomInteger[{5, 6}];
nvals = RandomInteger[{1, nmax}, len];
table = Table[RandomReal[{0, 1}, 2*nvals[[i]]], {i, 1, len, 1}];

DeveloperPackedArrayQ[res]


False

pack = DeveloperToPackedArray @ N @ res;

DeveloperPackedArrayQ[pack]


True

If you pad with a real value, -999.0 for example, you don't need the N.

SeedRandom[1];
len = 10;
nmax = RandomInteger[{5, 6}];
nvals = RandomInteger[{1, nmax}, len];
table = Table[Array[Subscript[\[Alpha], #] &, 2*nvals[[i]]], {i, 1, len, 1}];

Grid[table]


PadRight[table, Automatic, β] // Grid