# Error on using Compile[]

My code is below.

deltaX = 1/128;
W=256;
Mmax=40;

lPoly = ParallelTable[
LegendreP[
order, (-1.) + (deltaX/2.) + ((index - 1.)*deltaX)],
{order, 0, Mmax}, {index, 1, W}];

XPoly = Compile[{{index, _Integer}},
Block[{},
polyMatrix =
PadRight[Table[lPoly[[m - n + 1, index]], {m, 0, Mmax}, {n, 0, m}]];
polyMatrix], CompilationTarget -> "C",
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> {"CatchMachineIntegerOverflow" -> False}];


If I run XPoly[1], it will return:

CompiledFunction::cfse :  Compiled expression {{1.},{-0.996094,1.},<<48>>,<<71>>} should be a machine-size real number.


I have encountered this kinda error multiple times, sometimes it solved. But I dont know why.

• If you decide to turn to Compile, I suggest starting from reading this post: mathematica.stackexchange.com/a/104031/1871 And now you're against rule (2) and rule (6) there. – xzczd Jul 22 '20 at 3:10
• The main problem is that your Table constructs a ragged array (rows are are not all the same length). Ragged arrays are not allowed in Compile. – Michael E2 Jul 22 '20 at 3:42
• @MichaelE2 Thanks Mike. Actually I use PadRight here. For avoiding confusion, I didnt post it. If you mean constructing ragged array is not allowed, it would solve my problem. – PalvinWang Jul 22 '20 at 4:34
• Even with PadRight, you first generate a ragged array before it is padded. But you can apply PadRight outside of Compile to generate XPoly as rectangular array. Also make sure that all 0 are actually floating point 0.. (I am not sure whether Compile is clever enough to convert them on its own.) – Henrik Schumacher Jul 22 '20 at 4:55

This should work better: It generates a rectangular array (filled with zeroes) first and than fills in the entries:

deltaX = 1./128;
W = 256;
Mmax = 40;
lPoly = DeveloperToPackedArray[
Table[
LegendreP[order, -1. + 0.5 deltaX + (index - 1.) deltaX],
{order, 0, Mmax}, {index, 1, W}]
];

XPoly = Compile[{{index, _Integer}, {lPoly, _Real, 2}},
Block[{polyMatrix, Mmax},
Mmax = Length[lPoly] - 1;
polyMatrix = Table[0., {Mmax + 1}, {Mmax + 1}];
Do[
polyMatrix[[m + 1, n + 1]] = lPoly[[m - n + 1, index]]
,
{m, 0, Mmax}, {n, 0, m}];

polyMatrix
],
CompilationTarget -> "C",
RuntimeAttributes -> {Listable},
Parallelization -> True
];

test = XPoly[{1, 2, 3}, lPoly];
`
• Thanks a lot Henrik! – PalvinWang Jul 22 '20 at 12:27
• You're welcome! – Henrik Schumacher Jul 22 '20 at 12:30