creating a random vector of the values 0,1 with specific gaps
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Amos
am 9 Jan. 2015
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 Kommentare
Roger Stafford
am 10 Jan. 2015
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 Kommentare
Roger Stafford
am 10 Jan. 2015
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;
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!