1

I want to use the For syntax to turn the programme around for N generations. However, I am not quite sure how to use For syntax.

For example, the following list is available. This is the first generation, given an initial value of 10.

initialvalue = 10;
n = 10;

a = PoissonDistribution[initialvalue]; x = RandomVariate[a, n]; b = PoissonDistribution[initialvalue]; y = RandomVariate[b, n]; pairs = Transpose[{x, y}]; pairs = Flatten[RandomSample[pairs, 1], 1]

From the second generation onwards, the formula reflects the values of the previous generation rather than the initial values. The second generation is as follows.

a2 = PoissonDistribution[pairs[[1]]];
x2 = RandomVariate[a2, n];
b2 = PoissonDistribution[pairs[[2]]];
y2 = RandomVariate[b2, n];
f1pairs = Transpose[{x2, y2}];
f1pairs = Flatten[RandomSample[f1pairs, 1], 1]

The third generation is as follows.

a3 = PoissonDistribution[f1pairs[[1]]];
x3 = RandomVariate[a3, n];
b3 = PoissonDistribution[f1pairs[[2]]];
y3 = RandomVariate[b3, n];
f2pairs = Transpose[{x3, y3}];
f2pairs = Flatten[RandomSample[f2pairs, 1], 1]

How to make them calculate 100 times?

user64494
  • 26,149
  • 4
  • 27
  • 56
hare
  • 406
  • 1
  • 8

1 Answers1

2

Typically you want to avoid procedural loops like For in Mathematica, in favor of functional constructs. See for instance: Why should I avoid the For loop in Mathematica? and Alternatives to procedural loops and iterating over lists in Mathematica.

Instead this is a good use case for NestList:

ClearAll[iterator]
iterator[pair_, n_] :=
 Module[{zerofree, newpairs},
   newpairs = Transpose[RandomVariate[PoissonDistribution[#], n] & /@ pair];
   zerofree = Select[newpairs, FreeQ[0]];
   Flatten@RandomSample[zerofree, 1]
 ]

initialvalue = 15; n = 10;

NestList[iterator[#, n] &, {initialvalue, initialvalue}, 100]

{{15, 15}, {10, 22}, {11, 19}, {19, 15}, {21, 11}, {25, 9}, {29, 8}, {25, 14}, {20, 11}, {22, 10}, {25, 3}, {23, 3}, {22, 2}, {22, 2}, {24, 2}, {20, 2}, {20, 2}, {16, 1}, {15, 1}, {18, 2}, {12, 1}, {12, 1}, {14, 3}, {19, 3}, {16, 3}, {15, 2}, {11, 3}, {12, 5}, {12, 5}, {11, 5}, {9, 3}, {11, 5}, {11, 5}, {6, 12}, {5, 10}, {1, 13}, {1, 13}, {3, 14}, {2, 7}, {1, 4}, {1, 7}, {1, 8}, {1, 8}, {1, 7}, {1, 7}, {4, 5}, {5, 4}, {8, 2}, {6, 3}, {5, 7}, {4, 7}, {4, 5}, {4, 2}, {3, 1}, {4, 2}, {3, 2}, {3, 4}, {1, 4}, {1, 2}, {1, 2}, {4, 1}, {8, 1}, {5, 2}, {2, 3}, {1, 2}, {3, 1}, {3, 2}, {6, 1}, {2, 1}, {3, 1}, {1, 1}, {2, 4}, {5, 2}, {4, 5}, {5, 10}, {5, 5}, {6, 7}, {5, 7}, {7, 8}, {6, 7}, {7, 11}, {8, 14}, {6, 8}, {5, 5}, {6, 1}, {6, 1}, {2, 2}, {1, 1}, {4, 1}, {10, 3}, {16, 1}, {19, 1}, {15, 1}, {10, 2}, {11, 2}, {14, 2}, {10, 2}, {9, 2}, {8, 1}, {9, 1}, {11, 1}}

MarcoB
  • 67,153
  • 18
  • 91
  • 189