1

I am handling structures in the form:

struct('num', 2,
       'w1', 0.5,
       'w2', 0.5 );

contained in an array:

array = [struct1, struct2, ..., structN]

I would like to know whether it is possible to find automatically all the pairs of structures, as follows:

[struct1 struct2
 struct1 struct3
 ...
 struct1 structN
 struct2 struct3
 ...]

As a reference, I found this question for simple arrays.

Community
  • 1
  • 1
Eleanore
  • 1,750
  • 3
  • 16
  • 33

3 Answers3

2

Besides the obvious nchoosek solution, we can also get the indices a bit more creatively:

>> [j,i] = find(tril(true(N),-1));
>> pairs = array([i(:) j(:)])

The idea is to build a logical triangular matrix, and extract the row/column indices of the nonzero elements:

>> tril(true(5),-1)
ans =
     0     0     0     0     0
     1     0     0     0     0
     1     1     0     0     0
     1     1     1     0     0
     1     1     1     1     0

or

>> triu(true(5),1)
ans =
     0     1     1     1     1
     0     0     1     1     1
     0     0     0     1     1
     0     0     0     0     1
     0     0     0     0     0

depending on which order you want for the indices.

Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454
0

Try the allcomb.

Example:

a = [struct1, struct2, ..., structN];
allcomb(a(:))
lakshmen
  • 28,346
  • 66
  • 178
  • 276
0

You can use nchoosek to get indices of all pairs

result = array( nchoosek( 1:N, 2 ) );
Shai
  • 111,146
  • 38
  • 238
  • 371