Re: creating an array in a loop

*To*: mathgroup at smc.vnet.net*Subject*: [mg100482] Re: creating an array in a loop*From*: Bill Rowe <readnews at sbcglobal.net>*Date*: Fri, 5 Jun 2009 03:03:11 -0400 (EDT)

On 6/4/09 at 3:32 AM, ir12 at mail.gatech.edu (Igor R.) wrote: >I am new to Mathematica programming I have the following question. >How to create an array in a loop? I have the code >======================================== >Neps0; Nlmbd=10; >Array[SOL,{10,20}] >deps0=0.1; eps0=0.0; >For[lmbd=0; ieps0=1;, \ >lmbd<=Nlmbd-1; ieps0 <= Neps;, \ >lmbd=lmbd+1; ieps0=ieps0+1;,\ >eps0=deps0*(ieps-1); >SOL[[lmbd+1,ieps]]=Func[lmbd,eps0]; >] > >SOL >======================================== >(where Func[a,b] is some function) >What is wrong with it, why this does not work? I am guessing you intended to have two criteria for determining when the loop ends. Specifically, lmbd =E2=89=A4 Nlmbd-1 and ieps0 =E2=89= =A4 Neps0. But you have used a complex expression to join these two criteria. Mathematica will only see the result from the last. That is your exit criteria written as: lmbd<=Nlmbd-1; ieps0 <= Neps0; will not never output either a True or False value. That is you cannot use a semicolon to join test criteria. Nor can you use it to terminate your test criteria. Assuming I have correctly interpreted your intent, the loop test needs to be either lmbd =E2=89=A4 Nlmbd-1 && ieps0 =E2=89=A4 Neps or And[lmbd =E2=89=A4 Nlmbd-1, iesp0 =E2=89=A4 Neps0] It looks like you may have typos in the loop code. You have variables in your loop named similar to loop counters but not identical. Possibly, this is correct and you have these variable defined elsewhere or perhaps this is an error. I can't determine which is the case for certain. =46inally, while it is possible to do what you want using For loops, this tends to be very inefficient in Mathematica. Other constructs generally execute far faster than For loops while still generating the same result. For example consider the following: In[2]:= Timing[For[n = 0; sum = 0, n < 10^6, n++; sum += n]; sum] Out[2]= {3.41602,500000500000} In[3]:= Timing[Plus @@ Range[10^6]] Out[3]= {0.284018,500000500000} In[4]:= Timing[Total[Range[10^6]]] Out[4]= {0.235723,500000500000} In[5]:= Timing[Sum[n, {n, 10^6}]] Out[5]= {0.242449,500000500000} In[6]:= Timing[Sum[k, {k, m}] /. m -> 10^6] Out[6]= {0.000392,500000500000} All produce exactly the same result. But there is a vast difference in execution time with the For loop being the slowest.