MathGroup Archive 2005

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

Search the Archive

Re: help working with functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg60010] Re: [mg59987] help working with functions
  • From: ggroup at sarj.ca
  • Date: Sun, 28 Aug 2005 03:07:47 -0400 (EDT)
  • References: <200508270811.EAA15266@smc.vnet.net>
  • Reply-to: ggroup at sarj.ca
  • Sender: owner-wri-mathgroup at wolfram.com

On Saturday, August 27, 2005 at 04:11 GMT -0400, special agents were
informed that Hawkmoon269 leaked:

> My sense,though, is that this is inelegant newbie code and am
> interested in hearing alternative ways to program with the same output.
>  Also, I would like to generalize this as a callable function with
> arguments i,j,n...something like:

> f[i_,j_,n_]:=
> Clear[a]; Clear[seq];
> seq = Array[a,n,0]; a[0]=0; a[1]=1
> Do[a[k] = a[k-1] + a[k-2] + i j^(k-2), {k,2,n}]
> seq


You need to enclose your program somehow, either with () or a more
complex construct like Block or Module.  So one solution would be:

f[i_, j_, n_] := Module[{a, seq},
 seq = Array[a, n, 0]; a[0] = 0; a[1] = 1;
 Do[a[k] = a[k - 1] + a[k - 2] + i j^(k - 2), {k, 2, n}];
 seq]

If you start running this function a lot, you are going to generating
new variables stored in memory every time it is run. Another option
would be something like: 

f[i_, j_, n_] := Module[{a, m},
    a[0] = 0;
    a[1] = 1;
    a[k_] := a[k - 1] + a[k - 2] + i j^(k - 2);
    Table[a[m - 1], {m, 1, n}]
    ]

This is a pretty simple calculation, but if the calculation were slow,
you could try a variation:

f[i_, j_, n_] := Module[{a, m},
    a[0] = 0;
    a[1] = 1;
    a[k_] := a[k]= a[k - 1] + a[k - 2] + i j^(k - 2);
    Table[a[m - 1], {m, 1, n}]
    ]



  • Prev by Date: Re: ListDensityPlot and transparency
  • Next by Date: Re: ControlSystems Wolfram application. Does it support root locus for discrete time systems?
  • Previous by thread: help working with functions
  • Next by thread: Re: help working with functions