matlab - 在 MatLab 中迭代固定总和的值

标签 matlab combinatorics loops

假设我有 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/

相关文章:

matlab - 用MATLAB写一个二维实现牛顿法的函数

php - 我可以在网站上运行 MATLAB 代码吗?

Matlab:如何在matlab中使用PCA找到可以丢弃数据集中的哪些变量?

r - 与 data.table 连接的排列

python - 如何在 python 中实现一个简单的基于贪心多重集的算法

linux - Grep 用于多个目录的关键字并移动找到的文件

javascript - 将元素添加到已评估的循环中

matlab - 使用polyfit来预测物体掉落的位置?

algorithm - 复杂的组合算法

r - 根据 R 中 V2 中设置的条件计算 V1 列中的值之和