1

I found this solution by @Lambdageek to the problem of generating pairs of the elements of a vector in Matlab:

[p,q] = meshgrid(vec1, vec2);
pairs = [p(:) q(:)];

However I want to generate unique pairs from the elements of a vector, let's say [1 2 3]. [1 2] and [2 1] I would consider as duplicates of the same pair and I want to ignore the order of the pair elements.

1 2
1 3
2 1
2 3 
3 1
3 2

should reduce to:

1 2
1 3
2 3

Does anyone know an elegant solution to this? Thanks!

Community
  • 1
  • 1
solimanelefant
  • 546
  • 1
  • 5
  • 17

3 Answers3

4

You can sort each row and then look for unique rows:

uniquepairs = unique(sort(pairs,2), 'rows')

This works fine even if you have more than two columns.

For your example this returns

uniquepairs =
     1     2
     1     3
     2     3
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
3

Say the length of the vectors are n, use upper triangular matrix to generate a mask:

[p, q] = meshgrid(1:n, 1:n);
mask   = triu(ones(n), 1) > 0.5;
pairs  = [p(mask) q(mask)];
prgao
  • 1,767
  • 14
  • 16
  • Does not appear to work for vectors in general. For example: `vec1 = 1:3, vec2 = 10:-1:8` will give the wrong result, and I wouldn't even know how to use this for vectors of unequal length. (As they were in the referenced question). – Dennis Jaheruddin Sep 27 '13 at 13:13
  • 1
    Just use `vector(pairs)` as the result. As for unequal length, well, the OP says "a vector", not "two vectors" – Luis Mendo Sep 27 '13 at 13:20
1

The easiest way is probably this:

uniquePairs = nchoosek(1:n,2)

Or, in terms of an arbitrary vector v:

uniquePairs = nchoosek(v,2)
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • As is, the solution won't generate pairs of elements from vectors. (Unless these happen to be `1:n`) – Dennis Jaheruddin Sep 27 '13 at 13:15
  • I followed @prgao using just vectors of the form `1:n`. I thought that was clear enough. But you're right, it's better to spell it out. Corrected. – Luis Mendo Sep 27 '13 at 13:17
  • There is still some spelling to do as it requires 2 input vectors (Judging from the original pair creation 1 element should be picked from the first, and 1 from the second) – Dennis Jaheruddin Sep 27 '13 at 13:19
  • @DennisJaheruddin Hmm I don't get what you mean. Why two vectors? The question says "generating pairs of the elements of a vector" – Luis Mendo Sep 27 '13 at 13:22