Re: Suggestions for translating a Do[] loop ...
- To: mathgroup at smc.vnet.net
- Subject: [mg69792] Re: Suggestions for translating a Do[] loop ...
- From: "astanoff" <astanoff at gmail.com>
- Date: Sat, 23 Sep 2006 04:44:43 -0400 (EDT)
- References: <eevtpj$hfr$1@smc.vnet.net>
David Annetts wrote:
> Hi,
>
> Given that a, b & r are lists of the same length, can anyone suggest a
> translation of the following Do[] loop to something functional? It looks
> like an ideal application for Fold, but for me, the loop going backwards is
> really obscuring things.
>
> The loop is
>
> Do[
> r[[j]] = a[[j]] * (b[[j]] + r[[j + 1]]) / (1 + b[[j]] * r[[j
> + 1]]),
> {j, Length@a - 1, 1, -1}
> ];
>
> with r[[Length@a]] = 0.
>
> Many thanks,
>
> Dave.
A "functional" solution :
In[1]:=
a = Table[Random[],{5}];
b = Table[Random[],{5}];
aa[i_] := a[[i]];
bb[i_] := b[[i]];
rr[Length[a]] = 0;
rr[j_] := rr[j] = aa[j] * (bb[j] + rr[j + 1]) /
(1 + bb[j] * rr[j + 1]);
r = Reverse@Table[rr[j],{j,Length[a],1,-1}]
Out[1]=
{0.147028,0.184133,0.077559,0.519274,0}
hth
v.a.