Randperm a completely different set of numbers each loop

1 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2017-8-30
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

更多回答(2 个)

James Tursa
James Tursa 2017-8-30
编辑:James Tursa 2017-8-30
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.

Guillaume
Guillaume 2017-8-30
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 个评论
Jan
Jan 2017-8-30
Typos fixed:
currentset = [];
fullset = 1:100;
while true
newset = setdiff(fullset, currentset);
currentset = newset(randperm(length(newset), 10));
disp(currentset);
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by