1
$\begingroup$

I am learning Gibbs sampling and imitating this explanation. Can we use NestList,FoldList or any other iterative function instead of Do loop for this code?

With[{ρ = 0.8, n = 10000}, Do[θ1[1] = 1; θ2[1] = 1; 
  θ1[i + 1] = RandomVariate@NormalDistribution[ρ θ2[i], 1 - ρ^2];
  θ2[i + 1] = RandomVariate@NormalDistribution[ρ θ1[i + 1], 1 - ρ^2], {i, 1, n - 1}]]

sim = Table[{θ1[i], θ2[i]}, {i, 1, 10000}];

Animate[Show[
  ListStepPlot[Take[sim, i], 
   Epilog -> {Red, PointSize[0.01], Point[Take[sim, i]]}, 
   Frame -> True, Axes -> False, PlotRange -> {{-3, 3}, {-3, 3}}], 
  ContourPlot[
   PDF[MultinormalDistribution[{0, 0}, {{1, 0.9}, {0.9, 1}}], {x, 
     y}], {x, -2, 2}, {y, -2, 2}, PlotRange -> All, PlotPoints -> 25, 
   ContourShading -> None]], {i, 1, 100, 1}, 
 AnimationRunning -> False]
$\endgroup$
5
  • $\begingroup$ Why would you want to rewrite this without Do? You look only consists of side-effects (assigning a value). NestList can be used, but I don't see that it is more appropriate here. Btw, you are assigning \[Theta]1[1] = 1; and \[Theta]2[1] = 1; over and over again inside the loop. That is not necessary. $\endgroup$
    – halirutan
    Jan 18, 2018 at 3:28
  • $\begingroup$ Ah, OK, I looked over the rest of your code. It seems your whole approach is not ideal and can be simplified. Sorry for the confusion. $\endgroup$
    – halirutan
    Jan 18, 2018 at 3:29
  • $\begingroup$ I was just curious whether it can be done using more functional form. I am fine with Do loop. Thanks for suggestion for thetas, I'll put them outside of Do loop. $\endgroup$ Jan 18, 2018 at 3:33
  • $\begingroup$ When I write With[{\[Rho] = 0.8, {\[Theta]1[1], \[Theta]2[1]} = {1, 1}, n = 10000},Do[...stuff...]] I get error. Do I have to write this outside of With? {\[Theta]1[1], \[Theta]2[1]} = {1, 1}; Can use Block? $\endgroup$ Jan 18, 2018 at 3:47
  • $\begingroup$ Try With[{ρ = 0.8, n = 10000}, θ1[1] = 1; θ2[1] = 1; Do[*stuff*] ]. $\endgroup$ Jan 18, 2018 at 5:10

1 Answer 1

4
$\begingroup$

Here is an approach with NestList. It should be equivalent to what you are achieving with the Do loop.

Module[{ρ = 0.8, n = 10000, nf},
  nf[arg_] := RandomVariate@NormalDistribution[ρ arg, 1 - ρ^2];
  sim = NestList[With[{theta1 = nf[#[[2]]]}, {theta1, nf[theta1]}] &, {1, 1}, n-1]
  ];

enter image description here

$\endgroup$
1
  • $\begingroup$ I see now. Do loop is more appropriate and more readable for this kind of iteration. $\endgroup$ Jan 18, 2018 at 3:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.