Randperm a completely different set of numbers each loop
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Jan
on 30 Aug 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 Comments
More Answers (2)
James Tursa
on 30 Aug 2017
Edited: James Tursa
on 30 Aug 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 Comments
Guillaume
on 30 Aug 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 Comment
Jan
on 30 Aug 2017
Typos fixed:
currentset = [];
fullset = 1:100;
while true
newset = setdiff(fullset, currentset);
currentset = newset(randperm(length(newset), 10));
disp(currentset);
end
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!