I have been wrapping my head about a question it may look simple to you. I want compile a function that depends on a number of undetermined variables as,

Compile[{{x, _Real}, {y, _Real}, {z, _Real}, {w,_Real},...}, Evaluate[f(x,y,z,w,..,)], 
 RuntimeAttributes -> {Listable}, RuntimeOptions -> "Speed", 
 Parallelization -> True]

Where {x,y,z,...} can be as long as needed. I have tried the simple exercise of doing,

list=Table[{var[[i]], _Re},{i,Length@var}];
Compile[list, Evaluate[f(x,y,z,w,..,)], RuntimeAttributes -> {Listable}, RuntimeOptions -> "Speed", Parallelization -> True]

but it does not seem to work since _Re needs to be symbolic? (I am asking but I do not know).

Thanks for your comprehension!


I found a solution thanks to: Evaluating arguments of module (inside compile)

This is what it worked for me:

Compile[Evaluate@({#, _Real} & /@ var), Evaluate[f(x,y,z,w,..,)], RuntimeAttributes -> {Listable}, RuntimeOptions -> "Speed", Parallelization -> True]
  • 3
    $\begingroup$ Why not just have your compiled function accept a list of reals? $\endgroup$ – J. M.'s ennui May 11 '20 at 10:17
  • $\begingroup$ Hi J.M. thanks for replying. I am not sure I understand what you mean. Are you asking to pass to compile a list of reals instead of a function? If this is the case, this does not work for me since the list is huge and I have to pass it many times. $\endgroup$ – Xisco May 11 '20 at 15:13

I think this is what @JM was suggesting:

cfun = Compile[{{list, _Real, 1}}, Sin[list]];

In other words, define your function to take a rank-1 tensor (i.e. a list) of reals; you do not need to specify the length beforehand! Then, just evaluate whatever you need on that list. For instance, here are two examples with lists of different lenghts:

(* {0.841471, 0.909297, 0.14112, -0.756802, ..., 0.992973, 0.636087, -0.305614}*)

(* {0.841471, 0.909297, 0.14112} *)
  • 1
    $\begingroup$ Once again, thanks for following through! $\endgroup$ – J. M.'s ennui May 12 '20 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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