500
500

Reputation: 6619

Recursive Function In Mathematica

Consider :

dist = Parallelize[
   Table[RandomVariate[NormalDistribution[]], {100000}]];

How could I create a recursive function such that :

Subscript[d, 1] = dist[[1]]

Subscript[d, 2] = .95 Subscript[d, 1] + dist[[2]]

Subscript[d, 3] = .95 Subscript[d, 2] + dist[[3]]

And do this till Subscript[d, 100000]

Thank You.

It is surprisingly the first time I run into this.

Upvotes: 2

Views: 628

Answers (2)

Mr.Wizard
Mr.Wizard

Reputation: 24336

Consider this:

dist = RandomVariate[NormalDistribution[], {100000}];

dist2 = Rest@FoldList[0.95 # + #2 &, 0, dist];

Subscript[d, x_] := dist2[[x]]

I don't normally use Subscript this way; I don't know what may break doing this. If you describe more of your problem, I may have an alternate suggestion.

Upvotes: 6

Simon
Simon

Reputation: 14731

How about using something like

In[1]:= dist = ParallelTable[RandomVariate[NormalDistribution[]], {100000}];//Timing

Out[1]= {0.15601, Null}

In[2]:= folded = FoldList[.95 #1 + #2 &, First@dist, Rest@dist]; // Timing

Out[2]= {0.056003, Null}

which you can compare to

In[3]:= Subscript[d, 1] = dist[[1]];
        Do[Subscript[d, n] = 0.95 Subscript[d, n - 1] + dist[[n]], 
           {n, 2, Length@dist}] // Timing

Out[3]= {1.09607, Null}

In[4]:= Table[Subscript[d, n], {n, 1, Length@dist}] === folded

Out[4]= True

Upvotes: 2

Related Questions