MathGroup Archive 2002

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

Search the Archive

Re: Setting up dummy variables

  • To: mathgroup at smc.vnet.net
  • Subject: [mg35930] Re: [mg35813] Setting up dummy variables
  • From: Omega Consulting <omega_consulting at yahoo.com>
  • Date: Thu, 8 Aug 2002 06:06:20 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

At 01:41 AM 8/2/2002, Christopher Maierle wrote:
>Hi all,
>
>How do I set up a function that behaves like the Mathematica function Sum 
>vis-a-vis
>its treatment of dummy variables?  For example I can define i=6 and then
>enter
>
>Sum[f[i],{i,1,n}]
>
>and mathematica will not make the substitution i->6 even though the output
>generally still involves the dummy variable i.  I figure this has something
>to do with Modules, Blocks, and Holds but I'm not sure how to put it all
>together.  Any help would be greatly appreciated.
>
>-chris

So what you want is this behavior:

In[1]:=
i=1;

In[2]:=
Sum[f[i],{i,0,5}]
Out[2]=
f[0]+f[1]+f[2]+f[3]+f[4]+f[5]

There are two things you need to do:
-Control the order of evaluation
-Temporarily substitute with a dummy variable

This will prevent the arguments from evaluating before we can use them.

In[3]:=
SetAttributes[MySum,HoldAll]

There are two holds we need to maintain. First, we must hold the first 
argument to prevent it from turning into f[1]. We do this by wrapping the 
function in Hold. Second, we must replace the iteration variable, but we 
need to replace the unevaluated form. We do this with HoldPattern. Then 
after the substitution we let evaluation occur by using ReleaseHold. Now 
you have a version of the function that you can iterate using the dummy 
variable.

In[4]:=
MySum[f_,{x_,xmin_,xmax_}]:=
   Module[{newf,tmp},
     newf=ReleaseHold[Hold[f]/.HoldPattern[x]:>tmp];
      Apply[Plus,Table[newf,{tmp,xmin,xmax}]]
     ]

In[5]:=
MySum[f[i], {i, 0, 5}]
Out[5]=
f[0] + f[1] + f[2] + f[3] + f[4] + f[5]

--------------------------------------------------------------
Omega Consulting
"The final answer to your Mathematica needs"

Spend less time searching and more time finding.
http://www.wz.com/internet/Mathematica.html



  • Prev by Date: Putting Tables into Graphics (once again)
  • Next by Date: Re: Parts in color
  • Previous by thread: Re: Setting up dummy variables
  • Next by thread: RE: Re: Setting up dummy variables