Random order with constraints

1 次查看(过去 30 天)
Cindie De Faria
Cindie De Faria 2020-1-27
How can i generate random orders of 2 types of stimuli (1:n=200 and 2:n=20) with a constraint : there can't be 2 stimuli of type 2 in a row ?
  1 个评论
Stephan
Stephan 2020-1-27
编辑:Stephan 2020-1-27
Cindies "answer" moved here:
What i want is a random list like:
stim1
stim1
stim2
stim1
stim1
stilm1
stim1
stim2......
With 200 stim 1 and 20 stim 2 (but never 2 stim 2 in a row in the list)
OR random positions for the 20 stim2
so like :
5, 17, 77, 99, 201, 174...
so 20 random numbers between 1 and 220 but i want to make sure there are never numbers that follow each other (ex: 77 and 78) and that the number doesn't appear twice
Is that clear ?

请先登录,再进行评论。

回答(1 个)

the cyclist
the cyclist 2020-1-27
If you have the Statistics and Machine Learning Toolbox, you could do it like this:
x = sort(randsample(220,20,false));
while min(diff(x)) <= 1
x = sort(randsample(220,20,false));
end
This is a little ugly and fairly inefficient. The algorithm generates the 20 numbers, then checks them for the constraint, and repeats the process as necessary.
I did a bit of testing, and only about 15% of the random sequences will obey the constraint, so the while loop will typically run several times. But maybe that is OK.
I'm guessing there is a more clever way that is more efficient, but it did not come to me immediately.
You can do the same thing with base MATLAB like this:
x = randperm(220);
x = sort(x(1:20));
while min(diff(x)) <= 1
x = randperm(220);
x = sort(x(1:20));
end

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by