Group Abstract Group Abstract

Message Boards Message Boards

0
|
3.2K Views
|
5 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Creating Table of random integers?

Posted 2 years ago

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.

5 Replies

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
POSTED BY: Gianluca Gorni
Posted 2 years ago

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}}
POSTED BY: Bill Nelson

Thank you, that fixed it

Posted 2 years ago

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.

POSTED BY: Eric Rimbey

This is a language translation issue, between English and Mathematica code.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard