【问题标题】:all combination of indices of vectors with different lengths in MATLABMATLAB中具有不同长度的向量索引的所有组合
【发布时间】:2012-11-17 17:45:18
【问题描述】:

我有一个一维元胞数组 Z。Z 的每个元胞都包含一个向量。例如:

Z{1} = [1 2];
Z{2} = [3 4 5];
Z{3} = [6];
...
Z{length(Z)} = [10 11 12 13];

这些向量的大小都是不同的。我想要做的是将所有可能组合的函数值的总和与每个 Z{i} 中的一个元素进行比较。那就是我想比较以下所有组合:

func(1) + func(3) + func(6) + ...
func(1) + func(4) + func(6) + ...
func(1) + func(5) + func(6) + ...
func(2) + func(3) + func(6) + ...
func(2) + func(4) + func(6) + ...
func(2) + func(5) + func(6) + ...
...
...

我想知道哪种组合产生的最大值。

我怎样才能巧妙地做到这一点?越聪明越好。但我也在寻找任何工作代码。问题规模会很小。

注意:本例中使用的实际值,1、2、3、4、5、6、...只是示例。它们没有任何特定的模式。

【问题讨论】:

    标签: matlab combinations


    【解决方案1】:

    考虑以下解决方案,它有一个循环,但它会及时线性执行您想要的操作,而不是指数地

    迭代地,算法在Z 的所有行中运行,在Z{i} 行的条目中生成所有可能的路径。尽管如此,每个条目只解析一次,因此可以节省复杂性。

     N = 3;
    
     Z = cell(1,N);
    
     Z{1} = [1 2];
     Z{2} = [3 4 5];
     Z{3} = [6];
    
     f = @(x) x.^2;  %% Test function
    
    
    
    disp('init')
    res = arrayfun(f,(Z{1}))     %% Init step. Image of Z{1}
    for i = 2 : N
       disp(i)      %% just to have an idea of where you are in the process
       disp(res)
    
       t = bsxfun(@plus,res,arrayfun(f,(Z{i}))')  %In a tensor way you build all
                                                  %the possible sum of the res and f(Z{i})
                                                  %making all paths.
       res = reshape(t,1,[])                      %You put the tensor sum on a single
                                                  %row to be able to iterate.  
       disp('END step-------')
    end
    

    用正方形测试

    res =
    
    46    53    62    49    56    65
    

    例如46 = 1^2 + 3^2 + 6^249 = 2^2 + 3^2 + 6^2...

    到目前为止,我不确定您是否可以完全避免循环。我在这里所做的是动态地 构建解决方案,在每次迭代中添加一个单元格元素。

    张量求和技术(t = bsxfun(@plus,res,arrayfun(f,(Z{i}))'))来自this answer

    【讨论】:

    • 在这种情况下,我正在寻找的是: [1 3 6]^2, [1 4 6]^2, [1 5 6]^2, [2 3 6]^2 , [2 4 6]^2, [2 5 6]^2。我想你做了 [1 2]^2, [3 4 5]^2, [6]^2。
    • 知道了,所有可能的组合。好的
    • @Chang,你现在可能要考虑答案了。
    • @Chang,我添加了一些 cmets。
    • 非常感谢!但是,我怎么知道哪个组合产生最大的res
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 2019-05-31
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多