MathGroup Archive 2005

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

Search the Archive

Re: help working with functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg59993] Re: help working with functions
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Sun, 28 Aug 2005 03:07:31 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, U.K.
  • References: <dep7us$f1s$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

hawkmoon269 wrote:
> I have the following program written:
> 
> Clear[a]; Clear[seq];
> seq = Array[a,10,0]; a[0]=0; a[1]=1;
> Do[a[k] = a[k-1] + a[k-2] + 0 4^(k-2), {k,2,10}];
> seq
> 
> It works fine and correctly outputs
> 
> {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
> 
> 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
> 
> So that
> 
> f[0,4,10]
> 
> would output
> 
> {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}
> 
> I've tried variants of the foregoing, but can't get it to work
> correctly...
> 
> Many thanks in advance for ideas and assistance etc.
> 
> h
> 
Use *Module* inside your function rather than *Clear*; pay attention 
where to use commas and semi columns (they work just as the opposite as 
in C). Finally, you really should investigate how to code according to 
rule based and functional paradigms. Anyway, here is you function in 
procedural style:

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]

In[2]:=
f[0, 4, 10]

Out[2]=
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}

Best regards,
/J.M.


  • Prev by Date: Re: How to solve this type of equation in Mathematica?
  • Next by Date: Re: listplot two lists of different lengths
  • Previous by thread: Re: help working with functions
  • Next by thread: Keyboard problems - no "dead keys" - in Linux version of Mathematica