Pergunta

Assume I'm working with a binary vector {0,1}. I just want put as input argument something like p=[0,1] and have the exact number of zeros corresponding to the given probability (given the length of the vector, say 'N'), and I should have them in random order.

For example, with p=0.5 and N=8 i want to have something like [0 0 1 0 1 1 0 1], or [1 1 0 0 1 0 0 1], the important thing is to have 50% of zeros in random order. If necessary it should round when representation cannot be possibile (i.e. p=0.200034 and N=8).

I did X = (rand(1,N)<=(1-p)); but obviously it doesn't give always the exact density. Another solution is doing a for cicle, and visit in random order the vector using an accumulator, but I think there should be a better (faster) solution.

Thanks

Foi útil?

Solução

You can compute the number of ones, n; bulid a vector with n ones and N-n zeros (in that order); and then randomly permute that vector:

p = .5;
N = 8;

n = round(N*p); %// desired number of ones
result = [ ones(1,n) zeros(1,N-n) ]; %// n ones and N-n zeros
result = result(randperm(N)); %// random order

Outras dicas

You can use randsample to ransomly sample k = round( N * p ) entries from the vector and set them to 1:

function v = myBinSample( p, N )
k = round( p * N );
idx = randsample( N, k );
v = zeros(1, N);
v( idx ) = 1;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top