Generate 'k' vectors of unique (non-repetitive) integer random variables in the same range

1 次查看(过去 30 天)
Hi,
How can I generate two vectors of unique (non-repetitive) integer random variables (each vector with 50 components) in the range of [-80, 80]? What I wrote so far is this:
a = -80;
b = 80;
A = round((b-a).*rand(50,1) + a);
B = round((b-a).*rand(50,1) + a);
I need that the elements in A and B are unique, i.e., no element of A is in B, and reverse! But I don't know how to do that!
Thanks

采纳的回答

Guillaume
Guillaume 2015-11-19
There's no guarantee that successive calls to randperm will not create repetitions (after all after a while it would have to anyway), so use simply one call, and split it in two:
v = randperm(100, 90);
A = v(1:50); B = v(51:end);

更多回答(3 个)

Chris Turnes
Chris Turnes 2015-11-19
Will, given that you want integers in the range [-50 50] and are trying to generate 1000 numbers for both A and B, you're not going to be able to have ALL entries of A and B be unique. But check out randperm, as I think this is along the lines of what you're looking for.
  2 个评论
Antonio
Antonio 2015-11-19
编辑:Antonio 2015-11-19
You're right. Thanks for the point. I just revised my question! :) About the randpern, it's stated that: "For p = randperm(n,k), p contains k unique values." But when I write this:
A = randperm(100,45)
B = randperm(100,45)
the arrays are note unique! Any comment on that?!
Chris Turnes
Chris Turnes 2015-11-19
编辑:Chris Turnes 2015-11-19
Exactly what Guillaume wrote. If you want the range to be between -50 and 50, make the first input argument to randperm 101 and just subtract 51 off the result (note that if you use 100 and subtract 50, you'll get a result in [-49 50] and not [-50 50]):
v = randperm(101,90);
A = v(1:50) - 51;
B = v(51:end) - 51;

请先登录,再进行评论。


Image Analyst
Image Analyst 2015-11-19
Try this:
% Make 100 numbers in the range -80 to +80
data = randperm(161, 100) - 81
% Let's check the range.
fprintf('Actual range this run = [%d, %d]\n', min(data), max(data));
% Extract two vectors of 50 elements each.
A = data(1:50)
B = data(51:end)

John D'Errico
John D'Errico 2015-11-19
Simple, and without even loops for the whole set.
range = -80:80;
[~,tags] = sort(rand(1000,numel(range)),2);
A = range(tags(:,1:50));
B = range(tags(:,51:100));
Note that each row of A will be completely disjoint from the corresponding elements in that row of B. Of course, there will be some replicates if we compare one row to another, but that is a given since we have only 161 possible numbers and 1000 samples.

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by