How should I randomly generate pairs of non-identical natural numbers that should also be non-repeating?

6 vues (au cours des 30 derniers jours)
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.

Réponse acceptée

Walter Roberson
Walter Roberson le 18 Juin 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.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by