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

2 views (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 19 Nov 2015
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);

More Answers (3)

Chris Turnes
Chris Turnes on 19 Nov 2015
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 Comments
Antonio
Antonio on 19 Nov 2015
Edited: Antonio on 19 Nov 2015
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 on 19 Nov 2015
Edited: Chris Turnes on 19 Nov 2015
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;

Sign in to comment.


Image Analyst
Image Analyst on 19 Nov 2015
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 on 19 Nov 2015
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.

Community Treasure Hunt

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

Start Hunting!