I have a 3d array
and each dimension contains 7 elements(Overall 7*7*7= 343
elements). Each element contains a number between 0
and 1
which is the weight of that cell :
pop = sample(1 : 100, 7 ** 3, replace = TRUE)
prob = array(pop / sum(pop), c(7,7,7))
Now, I need to randomly select one cell of this array based on the weight of each elements .
But, i don't know how to select a cell randomly. I wish the proper response returns 3 different numbers between 1
to 7
.
For example, if it returns 2,4,3
then i figure out it is the cell with coordination of 2,4,3
The following works:
arrayInd(sample(1:343,1,prob = prob),c(7,7,7))
sample(1:343,1,prob = prob)
selects a number between 1:343 with the requisite probabilities, after which arrayInd()
turns that number into a vector of indices.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.