MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: odd delay problem

  • To: mathgroup at smc.vnet.net
  • Subject: [mg93172] Re: odd delay problem
  • From: David Bailey <dave at Remove_Thisdbailey.co.uk>
  • Date: Thu, 30 Oct 2008 02:00:35 -0500 (EST)
  • References: <ge9f2e$973$1@smc.vnet.net>

Michael Mandelberg wrote:
> I am running v. 6.0.3.0
> 
> I am having some weirdness where I will do something like:
> 
> G=Array[f,100];
> For[i=1, i<=100, i++,
>    f[i] = some calculation]
> 
> Then I will look at the result:
> 
> ListLinePlot[G]
> 
> The strange thing is, if I rerun this, but change 'some calculation'
> to 'some other calculation', then rerun the plot, the plot stays the
> same.  If I rerun the loop again, then the plot will change as
> expected.  What's going on here?  Why isn't it "taking" the first time?
> 
Wow - this is a muddle arising out of several misconceptions! First, 
here is a correct version of this code:

G=Array[0&,100];
  For[i=1, i<=100, i++,
     G[[i]] = some calculation]

Note that G is an array, and you might as well assign its elements 
directly. However, the syntax for array subscripts requires double 
square brackets.

Now lets look at what happens when your code runs. For convenience, I 
have reduced the number of points to 5, and simply examine the value of 
G rather than plot it. I am using multiples of i to represent the 
various different calculations.

G = Array[f, 100]

In[2]:= G = Array[f, 5]

Out[2]= {f[1], f[2], f[3], f[4], f[5]}

At this point G is an array of symbolic elements because the function f 
is undefined, but then you provide an element by element definition of f:

In[5]:= For[i = 1, i <= 5, i++, f[i] = 2 i];
G

Out[6]= {2, 4, 6, 8, 10}

Here G has been fully evaluated and taken the point by point definition 
of f.

Now the second time that you evaluate your code - to do something else - 
f already has a value (the old one!), so G never passes through the 
symbolic intermediate step:

In[7]:= G = Array[f, 5]

Out[7]= {2, 4, 6, 8, 10}

In[8]:= For[i = 1, i <= 5, i++, f[i] = 20 i];
G

Out[9]= {2, 4, 6, 8, 10}

Of course, the loop has changed the value of f, so that if you execute 
the code a third time, you will get the second calculation!

Finally, lets do the job properly:

G=Table[5 i,{i,1,5}]

The Table command generates 5 answers by iterating through i and returns 
an array result which gets assigned to G.

If in doubt, look at the intermediate values in a calculation! Also 
distinguish clearly between an array and a function.

David Bailey
http://www.dbaileyconsultancy.co.uk



  • Prev by Date: Mathematica 6.0: good choice statistics for an MD thesis?
  • Next by Date: Re: Re: Hypergeometric2F1
  • Previous by thread: Re: odd delay problem
  • Next by thread: Re: odd delay problem