I have five elements A
, B
, C
, D
and E
.
The distance between each of the elements is given by the matrix below:
Distances =
[0 5 3 8 15;
5 0 7 5 20;
3 7 0 12 12;
8 5 12 0 8;
7 20 12 8 0]
I want to choose all combinations of elements such that the sum of distances is less than 10
.
It can be done recursively by:
- First find sets of 2-item eligible combinations.
- Then, find sets of 3-item eligible combinations by adding another item to the previously-found eligible 2-item combinations.
- Etc.
Doing it by hand for the above example I get the following combinations:
A,
B,
C,
D,
E,
A B,
A C,
A D,
B C,
B D,
D E,
A B C
How would I do this systematically in Octave, if the number of elements is large (say 250)?
This is a plain Octave (or Matlab) solution. The matrix
Distances
is as in the question. The algorithm builds a 0-1 matrixa
in which each column encodes a set with sum of distances less thanlimit
(for example 10).The matrix
a
is initialized with identity, because all one-elements subsets are admissible (sum of distances is 0). Then each column is pickedc = a(:,m);
and the possibility of adding another element is investigated (cand = c; cand(k) = 1;
means adding k-th element). Without loss of generality, it is enough to consider adding only the elements after the last current element of the set.The product
cand'*Distances*cand
is twice the sum of distances of the candidate setcand
. So, if it's less than twice the limit, the column is added:a = [a cand];
. At the end, the matrixa
is displayed in transposed form, for readability.Output:
With a 250 by 250 matrix, the performance will greatly depend on how large
limit
is. If it is so large that all or most of 2^250 sets qualify, this is going to run out of memory. (2^250 is more than 10^75, so I don't think you'd ever want to see anywhere near that many sets).And this is to have output in a more readable form:
Output: