MATLAB中不同长度的矢量索引的所有组合

时间:2012-11-17 17:45:19

标签: matlab combinations

我有一维的单元格数组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,......仅仅是示例。它们没有任何特定的模式。

1 个答案:

答案 0 :(得分:2)

考虑以下解决方案,它有一个循环,但它会按时线性而不是指数

迭代地,该算法在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 ...

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

来自this answer

张量求和技巧(t = bsxfun(@plus,res,arrayfun(f,(Z{i}))'))。