Skip to content
Prev 105895 / 398506 Next

sample "n" random positions from a matrix

Milton,

If I understand your problem correctly, you want to take (and store) a 
random sample of the indexes of a matrix for values equal to 1.  If 
that's the case the following may work for you:

m=matrix(sample(c(0,1),100*100,replace=T),nrow=100,ncol=100) #Creates matrix

idxsample=function(m,n){
   idx=which(m==1,F)#Index of positions of 1's in the matrix
   pos=sample(idx,n,replace=F)#Random sample of matrix indexes
   return(pos)
}

This call will sample and store 20 "positions" with value==1 in your matrix
pos=idxsample(m,n=20)

you can then use the resulting object to retrieve the values from your 
matrix i.e.
m[pos] (not surprisingly, all == 1)


I hope this helps,

Francisco


Dr. Francisco J. Zagmutt
College of Veterinary Medicine and Biomedical Sciences
Colorado State University
Milton Cezar Ribeiro wrote: