4
$\begingroup$
Compile[{}, ConstantArray[0, {1, 2, 3}], CompilationTarget -> "C"][]

yields CompiledFunction::cfte: Compiled expression {{{0,0,0},{0,0,0}}} should be a rank 2 tensor of machine-size integers. Trying to specify the correct type using

Compile[{}, ConstantArray[0, {1, 2, 3}], 
{{ConstantArray[_, {_, _, _}], _Integer, 3}}, CompilationTarget -> "C"][]

fails with the same error message.

What is wrong here, and how to fix it?

P.S.: ConstantArray[ConstantArray[0, {2,3}], 1] does work but is more of an ugly hack than a solution.

Mathematica 11.01 on MacOS X.

$\endgroup$
6
  • 2
    $\begingroup$ ConstantArray is not fully compilable, i.e. not compilable in all cases, see here. Just use Table[0, {1}, {2}, {3}]? $\endgroup$ Dec 30, 2016 at 14:27
  • $\begingroup$ @MariusLadegårdMeyer Thanks, using Internal`CompileValues[ConstantArray] as described there I get {HoldPattern[ ConstantArray[{System`CompileDump`type_, System`CompileDump`rank_}, {Integer, System`CompileDump`drank_}]] :> Internal`CompileTypeEvaluate[{System`CompileDump`type, System`CompileDump`rank + If[System`CompileDump`drank > 0, 2, 1]}]} which seems to explain the error. Do you know why the type specification did not work? I can use the table. $\endgroup$
    – mrupp
    Dec 30, 2016 at 14:43
  • $\begingroup$ I don't know, but I think that Mathematica simply does not have a rule to compile ConstantArray[_, {_, _, _}] even though you have specified the type, that is all. It still calls MainEvaluate after all. $\endgroup$ Dec 30, 2016 at 14:56
  • $\begingroup$ How about f := ConstantArray[0, {1, 2, 3}]; Compile[{}, f, {{f, _Integer, 3}}, CompilationTarget -> "C"][]? $\endgroup$
    – xzczd
    Dec 30, 2016 at 18:08
  • 1
    $\begingroup$ @xzczd, nice work-around for the type error. It still calls MainEvaluate though (as I assume you know, but maybe other readers do not), so if speed is the goal of compiling then one should be aware of that. $\endgroup$ Dec 30, 2016 at 22:34

1 Answer 1

0
$\begingroup$

Just don't use ConstantArray inside compile. Alternatives that are fully compilable are

Compile[{}, Table[0, {1}, {2}, {3}], CompilationTarget -> "C"][]

or

Compile[{}, Array[0 &, {1, 2, 3}], CompilationTarget -> "C"]

If you want to inject a static array into the compiled body, you can use

With[{arr = ConstantArray[0, {1, 2, 3}]},
 Compile[{}, arr, CompilationTarget -> "C"][]
]

In general, your question is too vague to tell what approach is appropriate in your case.

$\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.