假设我有 n 个弹珠,每个弹珠都可以是 8 种可能的颜色之一。我想迭代弹珠颜色组合的所有可能值。我怎样才能在 MatLab 中做到这一点?
例如,如果 n = 2,那么我想迭代:
2 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0
1 0 1 0 0 0 0 0
1 0 0 1 0 0 0 0
1 0 0 0 1 0 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 1
0 2 0 0 0 0 0 0
0 1 1 0 0 0 0 0
0 1 0 1 0 0 0 0
等等
编辑:
这就是一些伪代码的样子,但正如您所看到的,它非常草率。我对一种更简洁的方法感兴趣,并且不需要 if 语句...
for i8 = 0:1:n
for i7 = 0:1:n - i8
for i6 = 0:1:n - i8 - i7
for i5 = 0:1:n - i8 - i7 - i6
for i4 = 0:1:n - i8 - i7 - i6 - i5
for i3 = 0:1:n - i8 - i7 - i6 - i5 - i4
for i2 = 0:1:n - i8 - i7 - i6 - i5 - i4 - i3
for i1 = 0:1:n - i8 - i7 - i6 - i5 - i4 - i3 - i2
if i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 == n
i = [i1, i2, i3, i4, i5, i6, i7, i8]
end
end
end
end
end
end
end
end
end
最佳答案
这是解决方案(代码在 GNU/Octave 中进行了测试,它也应该在 Matlab 中工作)。 此代码源自Octave-Forge multinom_exp.m
function conf = marbin (nmar,nbin)
%% Returns the position of nmar in nbis, allowing the marbles to be in the same bin.
%% This is standard stars and bars.
numsymbols = nbin+nmar-1;
stars = nchoosek (1:numsymbols, nmar);
%% Star labels minus their consecutive position becomes their index
%% position!
idx = bsxfun (@minus, stars, [0:nmar-1]);
%% Manipulate indices into the proper shape for accumarray.
nr = size (idx, 1);
a = repmat ([1:nr], nmar, 1);
b = idx';
conf = [a(:), b(:)];
conf = accumarray (conf, 1);
关于matlab - 在 MatLab 中迭代固定总和的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9778644/