Below, there is an example how I tried to call the compiled function "position" (which i got from this link position) inside another one.

position = Compile[{{mat, _Integer, 2}, {elm, _Integer, 0}}, Module[{result = Internal`Bag[Most[{0}]], i, j}, 
Table[If[mat[[i, j]] === elm, 
  Internal`StuffBag[result, Internal`Bag[{i, j}]]], {i, 
  Length[mat]}, {j, Length[First[mat]]}];
 Internal`BagPart[pos, {1, 2}], {pos, 
  Internal`BagPart[result, All]}]], CompilationTarget -> "C", RuntimeOptions -> "Speed"];

Now, I try to call the position function inside another and I do this with the "With"-function.

Ex = With[{pos = position}, Compile[{{G0, _Real, 2}}, Module[{G = G0, P, n, p},
 P = {2, 5, 1, 6};
 n = Length[G];
 p = pos[G, #] & /@ {P[[2]], P[[3]]};
 ], CompilationTarget -> "C", 
CompilationOptions -> {"InlineCompiledFunctions" -> True}]];

My question is, whether there is another way of calling a compiled function inside another, maybe without defining this variable "pos" at the beginning?


1 Answer 1


The documentation states:

If you call other functions, Compile will typically not know what type of value they return. If you do not specify otherwise, Compile assumes that any other function yields an approximate real number value.

So to make this work you have to explicitly define position for Ex.

Ex = Compile[{{G0, _Real, 2}}, 
    Module[{G = G0, P, n, p}, P = {2, 5, 1, 6};
        n = Length[G];
        p = position[G, #] & /@ {P[[2]], P[[3]]};],
        {{position[_], _Integer}},
        CompilationTarget -> "C", 
        CompilationOptions -> {"InlineCompiledFunctions" -> True}

I can not really verify this, if this is working correctly (no Mma here), so please forgive me if there's something wrong. At least it shows how to call another compiled function without Block statement.

  • $\begingroup$ The answer does not work for my example, but that's my fault since my input for position is wrong. With the right input it's working. $\endgroup$
    – Carolin
    Jun 22, 2013 at 14:04
  • $\begingroup$ Glad to hear that. Thanks for accepting. $\endgroup$
    – Stefan
    Jun 22, 2013 at 14:23

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.