creating a random vector of the values 0,1 with specific gaps
1 次查看(过去 30 天)
显示 更早的评论
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!!!!
0 个评论
回答(2 个)
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.
0 个评论
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
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;
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!