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}]
]
- References:
- help working with functions
- From: "hawkmoon269" <rson@new.rr.com>
- help working with functions