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

2 visualizzazioni (ultimi 30 giorni)
Soudipan Maity il 18 Giu 2019
Commentato: Soudipan Maity il 20 Giu 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 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Walter Roberson il 18 Giu 2019
[A, B] = ndgrid(range);
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.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Soudipan Maity il 20 Giu 2019
Thank you very much. This is working perfectly to meet my current objective.

Accedi per commentare.

### Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by