Randperm a completely different set of numbers each loop
4 ビュー (過去 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
0 件のコメント
採用された回答
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
0 件のコメント
その他の回答 (2 件)
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.
0 件のコメント
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
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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!