Find a subset of unique permutations

I have many arrays A of varying length. For any given A, I'd like to find all the unique sets of three elements of A. For example, if A has five elements:
A = [5 6 2 4 7];
one combination of three elements in A is [5 6 2], another combination is [5 6 4], and so on. When I work this out manually I get these combinations:
5 6 2
5 6 4
5 6 7
5 2 4
5 2 7
5 4 7
6 2 4
6 2 7
6 4 7
2 4 7
The appearance of the solutions above makes me think there may be a clever way to use an identity matrix, but I can't quite think of how. Or perhaps there's a way to use perms, perhaps with sort and unique?
Can you think of a way to get all 3-element subsets of an array?

3 件のコメント

Geoff Hayes
Geoff Hayes 2015 年 5 月 7 日
Chad - why not use nchoosek as
nchoosek(A,3)
which returns the same ten subsets that you have shown above. Is using this function undesirable because of its limitations with larger arrays?
Joseph Cheng
Joseph Cheng 2015 年 5 月 7 日
hmm... well to use what you ask i've only gotten this far
A=[5 6 2 4 7]
pA = perms(A);
sA = sort(pA(:,1:3),2);
uA =unique(sA,'rows')
but it wouldn't be in the same number order of A.
Chad Greene
Chad Greene 2015 年 5 月 7 日
nchoosek it is. Somehow I'd never heard of that function. Thanks Geoff and Joseph!

サインインしてコメントする。

 採用された回答

Jos (10584)
Jos (10584) 2015 年 5 月 7 日

2 投票

Why not use NCHOOSEK?
A = [5 6 2 4 7];
nchoosek(A,3)
ans =
5 6 2
5 6 4
5 6 7
5 2 4
5 2 7
5 4 7
6 2 4
6 2 7
6 4 7
2 4 7

1 件のコメント

Chad Greene
Chad Greene 2015 年 5 月 7 日
Perfect! This function does exactly what I was looking for. Thanks Jos!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by