How should I randomly generate pairs of non-identical natural numbers that should also be non-repeating?
4 views (last 30 days)
Show older comments
Soudipan Maity
on 18 Jun 2019
Commented: Soudipan Maity
on 20 Jun 2019
I want to generate a set of 20 pairs of natural numbers (between a certain range) in which every pair should have two non-identical natural number, and no pair should be repeated in the set under any circumstances.
For example,
Range = 1:10
Formed Data Set of 5 pairs = (2 , 6) ; (5, 4); (1 , 9) ; (2 , 9) ; (5 , 1)
Any help in this regard would be highly appreciated.
0 Comments
Accepted Answer
Walter Roberson
on 18 Jun 2019
[A, B] = ndgrid(range);
mask = A==B;
A(mask) = []; B(mask) = [];
N = length(A);
p = randperm(N, 20);
pairs = [A(p); B(p)].';
The above works well enough when the range is small. When the range gets larger the amount of memory gets larger according to the square of the number of elements in the range. If the number of pairs to be selected grows slower than the number of elements in the range, then at some point it becomes more efficient to use selection with rejection -- select pairs randomly, reject those that do no fit, select additional pairs as needed to reach the number of needed pairs. When the range is small compared to the number of pairs to be selected, that becomes increasingly poor and the non-rejection method I posted becomes better.
More Answers (0)
See Also
Categories
Find more on Random Number Generation 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!