Re: Compile can't handle indexed variables inside loops

*To*: mathgroup at smc.vnet.net*Subject*: [mg114305] Re: Compile can't handle indexed variables inside loops*From*: Daniel Lichtblau <danl at wolfram.com>*Date*: Tue, 30 Nov 2010 04:06:08 -0500 (EST)

Frank K wrote: > Indexed variables are renamed. This is ok if they aren't inside a > loop > > In[1]:= fc1 = Compile[{x[1],x[2]},x[1]+x[2]] > > Out[1]= CompiledFunction[{x$651,x$652},x$651+x$652,-CompiledCode-] > > In[2]:= fc1[1,2] > > Out[2]= 3. > > Indexed variables are not renamed inside a loop, so the function > fails. > > In[3]:= fc2 = Compile[{x[1],x[2]},Sum[x[i],{i,2}]] > > Out[3]= CompiledFunction[{x$655,x$656},\!\( > \*UnderoverscriptBox[\(\[Sum]\), \(i\), \(2\)]\(x[i]\)\),- > CompiledCode-] > > In[4]:= fc2[1,2] > During evaluation of In[4]:= CompiledFunction::cfex: Could not > complete external evaluation at instruction 5; > proceeding with uncompiled evaluation. >> > > Out[4]= x[1]+x[2] I cannot imagine how Compile might do otherwise, if it is passed a scoped construct such as Sum. (How would it change Sum to deal with these "new" variables? What if the sum index exceeds the number of "indexed" variables?) You might in some cases achieve a similar effect by treating the variables as a table, both in the Compile input variables lists and in the body of Compile code. tab = Table[x[i],{i,2}]; fc3 = With[{vars=tab},Compile[Evaluate[vars],Total[vars]]]; In[25]:= fc3[1,2] Out[25]= 3. Daniel Lichtblau Wolfram Research