合计总计 [英] combinations totaling to sum
问题描述
如何去生成一个矩阵,将所有可能的数字组合重复生成一个总和?
How would one go about generating a matrix with all the possible combinations of number totaling to a sum with repetition?
基本上,x1
,x2
,x3
的组合是x1 + x2 + x3 = n
.
Basically, combinations of x1
, x2
, x3
such that x1 + x2 + x3 = n
.
例如:n =3
0 1 2
0 2 1
1 0 2
1 2 0
1 1 1
是否有使用预定义的Matlab函数执行此操作的简单方法?
Is there simple way of doing this using predefined Matlab functions?
我尝试过
n=6;
nchoosek(0:n,3)
这给了我
0 1 2
0 1 3
0 1 4
0 1 5
0 1 6
0 2 3
0 2 4
0 2 5
0 2 6
0 3 4
0 3 5
0 3 6
0 4 5
0 4 6
0 5 6
1 2 3
1 2 4
1 2 5
1 2 6
1 3 4
1 3 5
1 3 6
1 4 5
1 4 6
1 5 6
2 3 4
2 3 5
2 3 6
2 4 5
2 4 6
2 5 6
3 4 5
3 4 6
3 5 6
4 5 6
一个人将如何提取总数等于n
的所有行?
我认为线性索引或find
应该可以实现,但是我不知道该怎么做.
How would one extract all rows that have the total equal to n
?
I think linear indexing or find
should make it possible, but I don't know how to go about that.
致谢
推荐答案
为具体起见,让我们来看3个值加起来等于6的示例.实现此目的的标准方法是考虑将2个除法器"放入一个每行6个相同的对象":这些分隔线将对象分成3组,您可以读取每组的长度.因此,我们需要做的就是列举所有放置分隔线的方法.您可以为此使用nchoosek(1:8, 2)
:该矩阵的每一行都通过描述2 + 6 == 8
对象+分隔线之间的2个分隔线的位置来描述一个分隔.
For concreteness, let's go with your example of 3 values adding up to 6. The standard way to do this is to think of placing 2 'dividers' into a row of 6 identical 'objects': those dividers then divide the objects into 3 groups, and you can read off the length of each group. So all we need to do is enumerate all ways of placing those dividers. You can use nchoosek(1:8, 2)
for this: each row of that matrix describes a division, by describing the positions of the 2 dividers amongst the 2 + 6 == 8
objects + dividers.
这是一种比枚举整数0-6的所有三元组,然后挑选出加到正确总数上的整数更有效的方法.
This is a more efficient approach than enumerating all triples of integers 0-6 and then picking out those that add to the correct total.
我并不是真的会说MATLAB,所以以下内容可能是单篇的(欢迎提出改进建议!),但类似的东西应该可以工作:
I don't really speak MATLAB, so the following is probably unidiomatic (and suggestions to improve it are welcome!), but something like this should work:
% Total we're aiming for.
n = 6;
% Number of pieces to divide that total into.
k = 3;
% All possible placements of internal dividers.
dividers = nchoosek(1:(n+k-1), k-1);
ndividers = size(dividers, 1);
% Add dividers at the beginning and end.
b = cat(2, zeros(ndividers, 1), dividers, (n+k)*ones(ndividers, 1));
% Find distances between dividers.
c = diff(b, 1, 2) - 1
这是此站点提供的结果:
c =
0 0 6
0 1 5
0 2 4
0 3 3
0 4 2
0 5 1
0 6 0
1 0 5
1 1 4
1 2 3
1 3 2
1 4 1
1 5 0
2 0 4
2 1 3
2 2 2
2 3 1
2 4 0
3 0 3
3 1 2
3 2 1
3 3 0
4 0 2
4 1 1
4 2 0
5 0 1
5 1 0
6 0 0
这篇关于合计总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!