Hi
I had the problem of getting all combinations of elements in a vector.
Here is a simple solution to the problem using recursive calls of a function:
And som demos:
I hope you find it usefull
I had the problem of getting all combinations of elements in a vector.
Here is a simple solution to the problem using recursive calls of a function:
Code:
mata:
function do_pairs(colvector v)
{
if ((R = rows(v)) > 2) {
return(J(R-1, 1, v[1]), (rest=v[2::R]) \ do_pairs(rest))
} else if (R == 2) {
return(v')
}
}
end
Code:
: do_pairs( ("a", "b", "c", "d")' )
1 2
+---------+
1 | a b |
2 | a c |
3 | a d |
4 | b c |
5 | b d |
6 | c d |
+---------+
: do_pairs( ("a", "b", "c")' )
1 2
+---------+
1 | a b |
2 | a c |
3 | b c |
+---------+
: do_pairs( ("a", "b")' )
1 2
+---------+
1 | a b |
+---------+
: do_pairs( ("a")' )
: do_pairs( (1::6) )
1 2
+---------+
1 | 1 2 |
2 | 1 3 |
3 | 1 4 |
4 | 1 5 |
5 | 1 6 |
6 | 2 3 |
7 | 2 4 |
8 | 2 5 |
9 | 2 6 |
10 | 3 4 |
11 | 3 5 |
12 | 3 6 |
13 | 4 5 |
14 | 4 6 |
15 | 5 6 |
+---------+


Comment