How can I ensure no repeated adjecent values in a vector?

1 次查看(过去 30 天)
Hello I've created a code in wich I generate an array of 52 values randomly of 1s and 2s with an 85% prob for 1s and 15% for 2s (approximately). Now I need to reorganize them in a way were I wont have 2s adjecent and at least two 1s before the next 2. to give you a better idea its this sequence: "1 1 1 1 2 1 1 1 1 2 1 1 1 2 1 1 1 1 2 1 1 2.....". This is to create an audio output for 1s and 2s. That means if x=1 the play A and X=2 Play B. Thats the idea behind it but I really need help with the second part.
My code is:
trials=[]
for i=1:5000;
test = rand_trial(0.85,52); % rand_trial is a function I made apart works fine
tbl = tabulate(test);
if tbl(1,2) == 44; % This is ne number of 1s I need for the trial
trials = test;
break
end
end
I would be most grateful for any help or advice.
Thanks in Advance

采纳的回答

Guillaume
Guillaume 2018-6-25
This is how I'd do it:
while true %run until we get an acceptable sequence. break will quit the loop
test = (randperm(52) > 44) + 1; %create a random permutation of 44 1s and 8 2s
if min(diff(find(test == 2))) > 3 %minimum distance between 2s is 3
break;
end
end
Note: rather than creating a distribution that has an 85% probability of 1s and then checking that there are exactly 44 1s, I just directly create a random permutation of 44 1s out of 52. In my opinion, it makes more sense.
  1 个评论
Juan Sanchez
Juan Sanchez 2018-6-25
@Guillaume Thank you kind sir, it works like a charm!! I am more than grateful with you! Thanks for the info and code

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by