I would like to create a list of compiled functions and then plot them 1 by 1. To illustrate the problem (In reality the functions I want to compile are of course not x^j but some complicated matrices):

cf = Table[Compile[{{x, _Real}}, x^j], {j, 1, 3}]

as output I get a list of compiled functions. Then I would like to plot one of them, for example the second:

Plot[cf[[2]][x], {x, -1, 1}]

During evaluation of In[107]:= CompiledFunction::cfse: Compiled expression j should be a machine-size integer. >>

During evaluation of In[107]:= CompiledFunction::cfex: Could not complete external evaluation at instruction 1; proceeding with uncompiled evaluation. >>

This is a bit weird since if I compile all those functions independently (without the use of a table around Compile) I can plot them nicely.

I hope this is not just a stupid syntax error, I am quite new to mathematica so please excuse me my probably stupid question :)



1 Answer 1


You need to use Evaluate inside the Compile call,

cf = Table[
  Compile[{{x, _Real}}, Evaluate[x^j]], {j, 1, 3}]

Plot[cf[[2]][x], {x, -1, 1}]

enter image description here

  • $\begingroup$ @march Interesting, I get the same error as OP $\endgroup$
    – Jason B.
    Feb 18, 2016 at 17:09
  • 1
    $\begingroup$ Nevermind. Didn't remove your Evaluate after copying and pasting. But Table[With[{j = j}, Compile[{{x, _Real}}, x^j]], {j, 1, 3}] still works. $\endgroup$
    – march
    Feb 18, 2016 at 17:19
  • $\begingroup$ @march, that's what I would've gone with, too; With[] is handy for injecting externally-produced stuff into a compiled function. $\endgroup$ Feb 18, 2016 at 17:41
  • $\begingroup$ @J.M. I agree that With is great, but the fact is that I use Evaluate every single time I use Compile. I can't think of a situation where I wouldn't do do it. If it were bash I would make an alias $\endgroup$
    – Jason B.
    Feb 18, 2016 at 17:55

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.