4
$\begingroup$

I am trying to use Module wrapped in a Compile to produce two outputs. One is a vector, the other is a matrix. My actual example is rather complicated, but I managed to find a simple example problem that shows my problem.

I want the compiled function hi to give me a list with two entries. One is a vector the other is a matrix. I attempted the following

hi = Compile[{{n, _Integer}},
   Module[{a, b},
    a = ConstantArray[2.0, {n, n}];
    b = ConstantArray[3.0, {n}];
    {a, b}
    ]
   ];

When I evaluate for instance hi[2] I get a message saying

CompiledFunction::cfex: Could not complete external evaluation at instruction 4; proceeding with uncompiled evaluation.

I understand that compile cannot deal with irregular arrays, but I only need this at the very end.

$\endgroup$
0
2
$\begingroup$

Well, this is not ideal because it requires global variables and because this won't allow you to use Parallelize -> True:

hi = Compile[{{n, _Integer}},
   Module[{a, b},
    a = Table[2.0, {n}, {n}];
    b = Table[3.0, {n}];
    
    (*further code*)
    
    $a = a;
    $b = b;
    ]
   ];

Then:

hi[3]
$a
$b

{{2., 2., 2.}, {2., 2., 2.}, {2., 2., 2.}}

{3., 3., 3.}

Make sure to copy the results to $a$ and $b only in the end because every access to $a$ and $b involves communication between the compiled function and the MathKernel and thus has some quite substantial overhead.

Also observe that ConstantArray is not compilable. But using table works as well.

$\endgroup$

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