Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 5 down vote accepted

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} *)
share|improve this answer
    
nice code and useful. Is there a limit on idx i.e. the dimension of in ? –  tchronis Dec 15 '13 at 14:45
    
@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. –  halirutan Dec 15 '13 at 14:50
2  
@Thomas What do you mean? It is your code! I thought you knew what you were writing!? –  halirutan Dec 15 '13 at 21:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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