Is MATLAB the best way to create a 2d array of unique pairs?

What is the best way to create a 10x2 matrix in matlab where each element is a random int between 1-5 and therefore there are only unique pairs of elements in this array? I know that randperm can give me random unique numbers, but Im not sure if randperm can be used to create unique pairs? The only way I can think of is to use:

randi([1 5], 10, 2); 

In a loop with an if statement checking if all pairs are unique. An example of the data I would like would be something like:

 4 5 1 3 2 2 1 4 3 3 5 1 5 5 2 1 3 1 4 3 

Note: the order of the elements does not matter, for example, both 4, 5, and 5, 4.

+7
arrays random matlab
source share
3 answers

First create all possible pairs as matrix rows, then use randperm to generate a random subset of row indices:

 N = 5; %// alphabet size M = 2; %// number of columns P = 10; %// desired number of rows allPairs = dec2base(0:N^M-1, N)-'0'+1; %// generate all possible rows ind = randperm(size(allPairs,1)); %// indices for random permutation of rows ind = ind(1:P); %// pick P unique indices result = allPairs(ind,:); %// use those indices to select rows 

Result:

 result = 3 2 1 4 3 5 4 1 1 3 1 2 2 4 3 4 5 5 1 5 
+5
source share

Here's another approach, using randperm and dec2base without the overhead of memory to create all possible strings (citing Luis solution ) -

 %// Inputs start = 1 stop = 5 Nr = 10 %// Number of rows needed Nc = 2 %// Number of cols needed intv = stop - start + 1; %// Interval/range of numbers rand_ID = randperm(power(intv,Nc)-1,Nr); %// Unique IDs out = dec2base(rand_ID,intv) - '0'+ start %// 2D array of unique numbers 

Run Examples -

Case No. 1 (the same parameters as indicated in the question):

 start = 1 stop = 5 Nr = 10 Nc = 2 out = 1 3 2 1 5 3 5 4 5 5 3 4 2 3 2 5 3 3 1 4 

Case No. 2 (different parameters):

 start = 1025 stop = 1033 Nr = 10 Nc = 5 out = 1030 1029 1033 1028 1029 1033 1029 1026 1025 1025 1028 1026 1031 1028 1030 1028 1031 1027 1028 1025 1033 1032 1031 1029 1032 1033 1029 1030 1027 1028 1031 1025 1032 1027 1025 1033 1033 1025 1028 1029 1031 1033 1025 1033 1029 1028 1025 1027 1028 1032 
+3
source share

Based on excaza comments, I found this to fit my needs:

 n = randperm(5); k = 2; data = nchoosek(n, k); 

Which gives an example output:

 2 3 2 4 2 1 2 5 3 4 3 1 3 5 4 1 4 5 1 5 
+1
source share

All Articles