1
$\begingroup$

Compile function output error: How to apply compiled function on list?

    mkCompileCode[vars_, code_, idx_] := 
    With[{fVars = Flatten[vars]}, 
    Compile[{{in, _Real, idx}}, Block[fVars, fVars = Flatten[in];
    code], RuntimeAttributes -> Listable]]

    vars = {x, y, z};
    df = Function[{x, y, z}, Sqrt[x^2 + y^2 + z^2] - 1];

Compiling the above function

    cdfs = mkCompileCode[vars, df, 1]

Compiled function does nt work on following list:

    p = {{-1.`, -1.`, -1.`}, {-1.`, -1.`, -0.75`}, {-1.`, -1.`, -0.5`}, 
         {-1.`, -1.`, -0.25`}};

    cdfs[p]

out:

   During evaluation of In[236]:= CompiledFunction::cfse: Compiled expression          
   Function[{x,y,z},Sqrt[x^2+y^2+z^2]-1] should be a machine-size real number. >>

  {Function[{x, y, z}, Sqrt[x^2 + y^2 + z^2] - 1], 
  Function[{x, y, z}, Sqrt[x^2 + y^2 + z^2] - 1], 
  Function[{x, y, z}, Sqrt[x^2 + y^2 + z^2] - 1], 
  Function[{x, y, z}, Sqrt[x^2 + y^2 + z^2] - 1]}

What's missing?

$\endgroup$
5
$\begingroup$

Please investigate again in your approach, because it is not clear why you use Function at this place

mkCompileCode[vars_, code_, idx_] := 
 With[{fVars = Flatten[vars]}, 
  Compile[{{in, _Real, idx}}, Block[fVars, fVars = Flatten[in];
    code], RuntimeAttributes -> Listable]];

vars = {x, y, z};
df = Sqrt[x^2 + y^2 + z^2] - 1;

cdfs = mkCompileCode[vars, df, 1];

p = {{-1.`, -1.`, -1.`}, {-1.`, -1.`, -0.75`}, {-1.`, -1.`, -0.5`}, {-1.`, -1.`, -0.25`}};

cdfs[p]

(* {0.732051, 0.600781, 0.5, 0.436141} *)
$\endgroup$
  • $\begingroup$ nice code and useful. Is there a limit on idx i.e. the dimension of in ? $\endgroup$ – tchronis Dec 15 '13 at 14:45
  • $\begingroup$ @tchronis There is always a limit, because we are working with machines having finite memory, but I'm not aware that the tensor rank (idx) is limited per definition. $\endgroup$ – halirutan Dec 15 '13 at 14:50
  • 2
    $\begingroup$ @Thomas What do you mean? It is your code! I thought you knew what you were writing!? $\endgroup$ – halirutan Dec 15 '13 at 21:41

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.