Is it possible to instruct Compile to take a list as arguments without having to hardcode each individual component of the list?
For example, suppose I want to take the dot product of a matrix and a vector:
Compile[{a,b,c,d,e,f,g},{{a,b},{c,d}}.{f,g}]
would do the trick, but notice the level of detail that I have to specify. Moreover, what if I do not know the dimension of the list I will feed to this function?
I guess a second-best solution would be to use meta functions inside Compile, something like
myComp[list1,list2]:=Compile[<some function that "separates" the elements from the lists>,<operation>]
Any guesses on what those meta functions should be?
Thank you, I didn’t notice that in the documentation when I was reading it.
However, I get inconsistent results when using the function. See attached notebook. Basically, it gives me an error the first few times that I try to use the compiled function, but after a few calls, it behaves as expected. What could be happening?
You have functions in your Compile statement which are defined outside it. At the least, you need to wrap the argument of Compile with Evaluate since Compile is HoldAll.
For C functions, Mathematica creates a library (dll or so) and then link it. The library is saved in a temporarily directory and removed when session ends. It is possible to copy created lib and use it latter. All relevant data needed to link the function:
SetDirectory[NotebookDirectory[]] ;
<< CompiledFunctionTools`;
F = Compile[{{x}},x^2+Sin[x^2],CompilationTarget->"C"];
F[[-1,1]] (* file location *)
F[[-1,2]] (* generic function name*)
F[[-1,3]] (* in arg *)
F[[-1,4]] (* out arg *)
Here is an example:
(* copy lib and get loading data *)
SaveFunc[name_,file_]:=Block[
{
data=Last[name]
},
CopyFile[
data[[1]],
StringJoin[file,".dll"] (* replace with .so on linux *)
];
{file,data[[2]],data[[3]],data[[4]]}
];
(* load lib *)
LoadFunc[savedata_]:=Block[
{ },
FindLibrary[Directory[]<>StringJoin["/",savedata[[1]]]];
LibraryFunctionLoad[
Directory[]<>StringJoin["/",savedata[[1]]],
savedata[[2]],
savedata[[3]],
savedata[[4]]
]
];
savedata = SaveFunc[F,"TEST"]
G = LoadFunc[savedata]
F[10.]
G[10.]
From my experience it is possible to use generated libs on other computers (of course you can’t use .dll on linux or .so on windows).
The only issue may be hardware dependent compilation of the lib, but default compiler flags do not do it.