向量列表,其元素的总和等于循环变量

发布于 2025-01-25 20:28:56 字数 282 浏览 1 评论 0原文

我想创建一个向量列表,其中列表中每个向量的元素总结到循环变量,而无需考虑元素和重复的顺序。 例如。

k=1, list ={[1]}; 
k=2, list ={[1,1],[2]}; 
k=3, list ={[1,1,1],[1,2],[2,1],[3]}; 
k=4, list ={[1,1,1,1],[1,3],[3,1],[2,2],[2,1,1],[1,2,1],[1,1,2],[4]};

等等。 列表的长度为$ 2^{k-1} $。在MATLAB中有什么简单的策略吗?

I want to create a list of vectors, where the elements of each vector in the list sums up to the loop variable without considering order of elements and repetition into account.
For eg.

k=1, list ={[1]}; 
k=2, list ={[1,1],[2]}; 
k=3, list ={[1,1,1],[1,2],[2,1],[3]}; 
k=4, list ={[1,1,1,1],[1,3],[3,1],[2,2],[2,1,1],[1,2,1],[1,1,2],[4]};

and so on.
The length of the list is $2^{k-1}$. Is there any easy strategy to do this in MATLAB?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒绊 2025-02-01 20:28:56

有一个简单的递归策略:如果您有一些具有一些k-1的整数分区列表,则很容易地使用SUM k生成分区:给定一些分区,我们可以附加1来创建一个新的分区,或者我们可以增加最后一个条目。

k = 5;
sumk = {[1]}; % anchor
for current_sum = 2:k    % recursion
    new_sumk = {};
    % (a) create new list by appending an 1
    new_append = cellfun(@(x)[x,1], sumk, 'Un', 0);
    % (b) create new list by increasing last element
    new_increment = cellfun(@(x)[x(1:end-1), x(end)+1], sumk, 'Un', 0)
    sumk = [new_append, new_increment];
end

% print the whole thing:
for l = 1:length(sumk)
    disp(sumk{l})
end

There is an easy recursive strategy: If you have a list of the integer partitions with the sum of some k-1, it is easy to generate the partitions with sum k: Given some partition, we can either append an 1 to create a new partition, or we can just increment the last entry., so something like this should work.

k = 5;
sumk = {[1]}; % anchor
for current_sum = 2:k    % recursion
    new_sumk = {};
    % (a) create new list by appending an 1
    new_append = cellfun(@(x)[x,1], sumk, 'Un', 0);
    % (b) create new list by increasing last element
    new_increment = cellfun(@(x)[x(1:end-1), x(end)+1], sumk, 'Un', 0)
    sumk = [new_append, new_increment];
end

% print the whole thing:
for l = 1:length(sumk)
    disp(sumk{l})
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文