Randperm a completely different set of numbers each loop
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Jan
il 30 Ago 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 Commenti
Più risposte (2)
James Tursa
il 30 Ago 2017
Modificato: James Tursa
il 30 Ago 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 Commenti
Guillaume
il 30 Ago 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 Commento
Jan
il 30 Ago 2017
Typos fixed:
currentset = [];
fullset = 1:100;
while true
newset = setdiff(fullset, currentset);
currentset = newset(randperm(length(newset), 10));
disp(currentset);
end
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!