Chose vectors (from a randomly generated vectors) which does not contain more than two identical elements
Mostrar comentarios más antiguos
I am generating a random vector of size 1x50 (using randi with range 1 to 400),several times(lets say 50000 times). But from these random vectors, I will chose only those vectors which does not contain more than two identical elements i.e. a vector having more than two identical elements will be thrown and rest will be saved in row wise matrix form. How to do this generally so that I can use the code for other cases(e.g. not more than four identical elements instead of two etc.)
1 comentario
Walter Roberson
el 9 de Mayo de 2017
I am not clear as to what exactly "not more than two identical elements" means, especially as you expand the number.
[1 1 1 1] -- contains 1 identical number? Contains 4 identical numbers?
[1 2 1 2] -- contains 2 identical numbers? Contains 4 identical numbers?
[1 2 3 1] -- contains 1 identical number? Contains 2 identical numbers?
Respuesta aceptada
Más respuestas (1)
v = [randperm(400, 25), randperm(400, 25)];
v = v(randperm(50, 50));
Now v contains 50 random values from 1 to 400 and no value appears more than 2 times.
v = randi([1, 400], 50);
[B, N] = RunLength(sort(v));
if any(N > 2)
% More than 2 occurrences of a certain value
...
Another alternative (not tested):
P = ones(1, 50);
while ...
v = randi([1, 400], 50);
S = splitapply(@sum, P, v)
if any(S > 2)
...
I assume the constructive randperm method is the fastest.
1 comentario
Kamal Bera
el 9 de Mayo de 2017
Categorías
Más información sobre Logical en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!