Random order with constraints

2 visualizaciones (últimos 30 días)
Cindie De Faria
Cindie De Faria el 27 de En. de 2020
Respondida: the cyclist el 27 de En. de 2020
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 comentario
Stephan
Stephan el 27 de En. de 2020
Editada: Stephan el 27 de En. de 2020
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 ?

Iniciar sesión para comentar.

Respuestas (1)

the cyclist
the cyclist el 27 de En. de 2020
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

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by