在 Matlab 中生成包含给定集合中至少一个元素的所有组合
我使用 combnk
生成组合列表。如何生成始终包含特定值的组合子集。例如,对于 combnk(1:10, 2)
我只需要包含 3 和/或 5 的组合。有没有快速的方法来做到这一点?
I use combnk
to generate a list of combinations. How can I generate a subset of combinations, which always includes particular values. For example, for combnk(1:10, 2)
I only need combinations which contain 3 and/or 5. Is there a quick way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,在您的具体示例中,从集合 {1, ..., 10} 中选择两个整数,其中所选整数之一为 3 或 5,会产生 9+9-1 = 17 个已知组合,因此您可以枚举它们。
一般来说,从包含整数 m 的整数 {1, ..., n} 中查找所有 n-choose-k 组合,这与查找 (n-1)-choose-(k-1) 相同整数 {1, ..., m-1, m+1, ..., n} 的组合。
在 matlab 中,这将是
(即使
m
为 1 或 n,此代码仍然有效。)Well, in your specific example, choosing two integers from the set {1, ..., 10} such that one of the chosen integers is 3 or 5 yields 9+9-1 = 17 known combinations, so you can just enumerate them.
In general, to find all of the n-choose-k combinations from integers {1, ..., n} that contain integer m, that is the same as finding the (n-1)-choose-(k-1) combinations from integers {1, ..., m-1, m+1, ..., n}.
In matlab, that would be
(This code is still valid even if
m
is 1 or n.)对于强力解决方案,您可以使用 COMBNK 生成所有组合然后使用函数 ANY 和 ISMEMBER 仅查找包含一个或多个数字子集的组合。以下是使用上面的示例执行此操作的方法:
编辑:
对于更优雅的解决方案,它看起来像 史蒂夫和我有类似的想法。不过,我已经概括了该解决方案,以便它既适用于任意数量的必需元素,也适用于
v
中的重复元素。函数 SUBCOMBNK 将查找取自集合v
的所有k
值的组合,其中至少包含集合vSub
中的一个值:您可以针对上面的暴力解决方案测试此函数,看看它返回相同的输出:
我使用
v = 1:15;
和vSub = 进一步针对暴力解决方案测试了此函数[3 5];
对于从 2 到 15 的N
值。创建的组合是相同的,但 SUBCOMBNK 的速度明显更快,如下面显示的平均运行时间(以毫秒为单位)所示:For a brute force solution, you can generate all your combinations with COMBNK then use the functions ANY and ISMEMBER to find only those combinations that contain one or more of a subset of numbers. Here's how you can do it using your above example:
EDIT:
For a more elegant solution, it looks like Steve and I had a similar idea. However, I've generalized the solution so that it works for both an arbitrary number of required elements and for repeated elements in
v
. The function SUBCOMBNK will find all the combinations ofk
values taken from a setv
that include at least one of the values in the setvSub
:You can test this function against the brute force solution above to see that it returns the same output:
I further tested this function against the brute force solution using
v = 1:15;
andvSub = [3 5];
for values ofN
ranging from 2 to 15. The combinations created were identical, but SUBCOMBNK was significantly faster as shown by the average run times (in msec) displayed below:只是为了改进史蒂夫的答案:在你的情况下(你想要所有与 3 和/或 5 的组合),它将是
可以轻松推广到该类型的任何其他情况。
Just to improve Steve's answer : in your case (you want all combinations with 3 and/or 5) it will be
Easily generalized for any other case of this type.