4
$\begingroup$

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,

var={x,y,z}
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!

UPDATE:

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]
$\endgroup$
2
  • 3
    $\begingroup$ Why not just have your compiled function accept a list of reals? $\endgroup$ Commented May 11, 2020 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
    Commented May 11, 2020 at 15:13

1 Answer 1

5
$\begingroup$

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:

cfun[Range[10000]]
(* {0.841471, 0.909297, 0.14112, -0.756802, ..., 0.992973, 0.636087, -0.305614}*)

cfun[Range[3]]
(* {0.841471, 0.909297, 0.14112} *)
$\endgroup$
1
  • 1
    $\begingroup$ Once again, thanks for following through! $\endgroup$ Commented May 12, 2020 at 2:39

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.