2
$\begingroup$

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)?

$\endgroup$
4
  • $\begingroup$ PadRight[table, {Automatic, 2 nmax}, -999]? $\endgroup$
    – kglr
    Nov 4, 2023 at 14:11
  • $\begingroup$ @kglr : Thanks! However, nmax is unknown a priori, we may extract it only from table. $\endgroup$ Nov 4, 2023 at 14:13
  • 1
    $\begingroup$ @kglr : also, Developer`PackedArrayQ[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. $\endgroup$ Nov 4, 2023 at 14:16
  • 2
    $\begingroup$ PadRight[table, Automatic, -999] $\endgroup$
    – kglr
    Nov 4, 2023 at 14:19

2 Answers 2

3
$\begingroup$

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}];

res = PadRight[table, Automatic, -999]

Developer`PackedArrayQ[res]

False

pack = Developer`ToPackedArray @ N @ res;

Developer`PackedArrayQ[pack]

True

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

$\endgroup$
3
$\begingroup$
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]

enter image description here

PadRight[table, Automatic, β] // Grid

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.