creating a random vector of the values 0,1 with specific gaps

조회 수: 1 (최근 30일)
shani peles
shani peles 2015년 1월 9일
댓글: shani peles 2015년 1월 10일
hey, I'm trying to creating a random vector of the values 0,1, in which 20% of the values are 1. I don't want to get two 1s in a row (e.x 0 0 1 1 0 0 0 0 0 0 ). does any one has an idea? thank u!!!!

답변 (2개)

Amos
Amos 2015년 1월 9일
Hi Shani, you could first generate a vector of 0 and 1 with the desired fraction of 1 and then check for each 1 if one of the neighbours is 1, too. If yes, give this one a new random position in the vector. Then you can proceed until no 1 has another 1 as neighbour.

Roger Stafford
Roger Stafford 2015년 1월 10일
There are two possible meanings you might have for the phrase "20% of the values are 1" :
1) The percentage of ones has a statistically expected (average) value of 20%.
2) The number of elements in the vector is a multiple of five and exactly 20% of these are ones.
Which of these meanings do you have in mind, Shani?
If the meaning is 1), (statistical) let n be the desired length of the vector, and do this:
V = zeros(n,1);
V(1) = ceil(rand-0.8);
for k = 2:n
if V(k-1) == 0
V(k) = ceil(rand-0.75); % The .75 is necessary to maintain 20% chance of ones
end
end
If the meaning is 2) (strictly 20%), let the desired length of V be n, a multiple of five, and do this:
k = n/5; % n must be an integral multiple of 5
V = zeros(n,1);
V((0:k-1)+sort(randperm(4*k+1,k))) = 1;
  댓글 수: 3
Roger Stafford
Roger Stafford 2015년 1월 10일
To avoid a 1 in the first element of V, change the code for meaning 2) to:
k = n/5; % n must be an integral multiple of 5
V = zeros(n,1);
V((1:k)+sort(randperm(4*k,k))) = 1;
shani peles
shani peles 2015년 1월 10일
thank you!!! you're awesome ;)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by