RE: dummy indicies
- To: mathgroup at smc.vnet.net
- Subject: [mg35903] RE: [mg35882] dummy indicies
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Wed, 7 Aug 2002 05:59:21 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Christopher Maierle [mailto:chris at chaos.Physik.uni-dortmund.de] To: mathgroup at smc.vnet.net >Sent: Monday, August 05, 2002 12:02 PM >Subject: [mg35903] [mg35882] dummy indicies > > >This is a repost of a question I asked last week. Apparently, I wasn't >clear about my problem. I have written a function that is similar to >the Mathematica function Sum in that the user needs to use >dummy indicies in order >to CALL the function. That is, one enters, > >mysum[f[i,j,k,...],{i,mini,maxi},{j,minj,maxj},{k,mink,maxk},...] > >The function works the way I want it to except that I must be certain >that the dummy variables i, j, k, etc... are not already defined in the >Global context. In other words, because I have not done anything special >in defining the function, Mathematica will substitute in any Global values that >exist for i, j, k, before using the arguments of mysum in a computation. > >I would rather be able to use dummy indicies without making sure that they >are not already defined. The Mathematica function Sum behaves this way. How >do I write a function like that? I figure this has something >to do with >setting attributes for mysum but I haven't been able to work out all the >details. Any help would be much appreciated. > >thanks in advance >-ciao > >-chris > Christopher, observe e.g. In[1]:= Attributes[mysum] = {HoldAll}; In[2]:= mysum[expr_, iters:({_Symbol, _, _}..)] := Sum[expr, iters] In[3]:= m = -5; n = m^2; i = I; In[4]:= mysum[Sin[x^m + y^n], {m, 1, 3}, {n, 1, m}] Out[4]= Sin[x + y] + Sin[x^2 + y] + Sin[x^3 + y] + Sin[x^2 + y^2] + Sin[x^3 + y^2] + Sin[x^3 + y^3] In[5]:= {m, n, i} Out[5]= {-5, 25, I} Or if you have to do everything by yourself: In[6]:= Attributes[mysum2] = {HoldAll}; In[7]:= mysum2[expr_, {i_Symbol, imin_, imax_}, {j_Symbol, jmin_, jmax_}] := Module[{s=0}, Block[{i = imin}, While[i <= imax, Block[{j = jmin}, While[j <= jmax, s += expr; ++j]]; ++i]]; s] In[8]:= mysum2[Sin[x^m + y^n], {m, 1, 3}, {n, 1, m}] Out[8]= Sin[x + y] + Sin[x^2 + y] + Sin[x^3 + y] + Sin[x^2 + y^2] + Sin[x^3 + y^2] + Sin[x^3 + y^3] -- Hartmut