I’m attempting to add a given number of random purturbations to a set. I can generate an empty 8x8 Table, and display it in matrix form. But something goes wrong when I attempt to populate it.
Also, if there’s a better way to do this, I’m all ears.
I’m attempting to add a given number of random purturbations to a set. I can generate an empty 8x8 Table, and display it in matrix form. But something goes wrong when I attempt to populate it.
Also, if there’s a better way to do this, I’m all ears.
This is a simple syntax issue.
RandomInteger[1, 8]
gives something like {1, 1, 1, 0, 1, 0, 1, 1}. If you want a random integer between 1 and 8, you use this:
RandomInteger[{1, 8}]
This is spelled out in the documentation for RandomInteger.
Thank you, that fixed it
Try
myTable=Table[0,{x,8},{y,8}];
For[population=100,population>0,population--,
x=RandomInteger[{1,8}];
y=RandomInteger[{1,8}];
myTable[[x,y]]=myTable[[x,y]]+1
];
myTable
and the result is
{{2,2,2,1,1,4,1,3},
{4,1,1,4,1,1,2,2},
{2,2,2,1,1,1,0,2},
{4,0,0,1,0,0,2,2},
{1,1,4,2,1,1,0,0},
{0,1,1,0,1,2,1,0},
{2,0,2,1,2,3,2,3},
{2,2,1,3,3,3,1,2}}
A functional programming approach:
population = 100;
choices = RandomChoice[Range[8*8], population];
cumulative = Tally[choices];
mySparseList =
SparseArray[cumulative /. {n_Integer, freq_} :> ({n} -> freq)];
myTable = Partition[Normal[mySparseList], 8]
Total@Total[myTable] == population
This is a language translation issue, between English and Mathematica code.