Randperm a completely different set of numbers each loop
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Shana Hartel
el 30 de Ag. de 2017
Respondida: Jan
el 30 de Ag. de 2017
I have randperm operating in a loop. Looking for a way to randperm a completely different set of numbers than the previous loop. Every other loop can share similar numbers, but consecutive loops cannot. I could brute force it and run a check to see if any of the new numbers were in the previous set (if so, run again, if not keep it) but maybe there is an easier way?
In otherwords, is there a way to have randperm exclude numbers from an array?
Thanks
0 comentarios
Respuesta aceptada
Jan
el 30 de Ag. de 2017
Guillaume's method without setdiff is 10 times faster:
curset = [];
fullset = 1:100;
for k = 1:1e4
newset = fullset;
newset(curset) = [];
curset = newset(randperm(length(newset), 10));
end
0 comentarios
Más respuestas (2)
James Tursa
el 30 de Ag. de 2017
Editada: James Tursa
el 30 de Ag. de 2017
If you mean the numbers can be the same but have to be in different spots, I suppose you could rotate the matching numbers to get the new set. E.g.,
% Setup
n = 10; % Some length
r_new = zeros(1,n);
% Code to generate new non-repeating set
r_old = r_new;
f = 1;
while( numel(f) == 1 )
r_new = randperm(n);
f = find(r_new==r_old);
end
if( numel(f) ~= 0 )
g = f([end,1:end-1]);
r_new(f) = r_new(g);
end
Whether this is worth it vs just brute force generate a new set ... I don't know.
0 comentarios
Guillaume
el 30 de Ag. de 2017
You can always setdiff your previous set from the set you pass to randperm:
currentset = [];
fullset = 1:100;
while true
newset = setdiff(fullset, previousset);
currentset = randperm(newset, 10);
disp(currentset);
end
1 comentario
Jan
el 30 de Ag. de 2017
Typos fixed:
currentset = [];
fullset = 1:100;
while true
newset = setdiff(fullset, currentset);
currentset = newset(randperm(length(newset), 10));
disp(currentset);
end
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!