【问题标题】:Possible combinations of numbers with variables sizes in matlab [duplicate]matlab中数字与变量大小的可能组合[重复]
【发布时间】:2014-07-27 20:07:26
【问题描述】:

我是 matlab 的初学者。 我有一个数字数组。说 5 (4,2,1,4,3) 这意味着变量 1 可以取 0 到 1 之间的值,变量 2 可以取值 1,2 变量 3 可以取 0 和 1,变量 4 可以取 0 到 4,变量 5 可以取 0 t0 3。

我尝试在 matlab 中使用“combntns”,但它是一个特定的,不像我的情况,每个变量都定义了一组数字。 我需要所有的组合。我尝试使用 for 循环

for a=i1:-1:0
    for b=i2:-1:0
        for c =i3:-1:0
            for d=i4:-1:0
                for e = i5:-1:0
               com(j,1)=a;
                com(j,2)=b;
                com(j,3)=c;
                com(j,4)=d;
                com(j,5)=e;
                j=j+1;                    
            end
        end
    end
end

我不想使用这么多 for 循环。如果我的数组大小增加到 100 个数字,那么编写 100 个 for 循环是一项非常艰巨的任务。 谁能给我一个代码?

【问题讨论】:

    标签: matlab combinations


    【解决方案1】:

    我设法通过以下方式递归地解决了您的问题:

    A = [ 0 1
          1 2
          0 1
          0 4
          0 3 ]; %// <= This is the example that you gave.
    
    out = recursivePermutations(A,[]);
    

    函数recursivePermutations是:

    function out = recursivePermutations(boundsMat,previousCombos)
    
    if size(boundsMat,1)==0
        out = previousCombos;
        return;
    else
       lowBound = boundsMat(end,1);
       uppBound = boundsMat(end,2);
       tmp = (lowBound:uppBound)';
    
       if ~isempty(previousCombos)         
           tmp = [repmat(previousCombos,[length(tmp),1]),...
              reshape(repmat(tmp',[length(previousCombos),1]),...
              length(previousCombos)*length(tmp),1)];
    
       end   
       out = recursivePermutations(boundsMat(1:end-1,:),tmp);
    end
    

    结果是一个大小为 160*5 的向量。这对应于您在此示例中应该获得的可能性数量 (2*2*2*5*4)。

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 1970-01-01
      • 2016-08-08
      • 2021-09-18
      • 2023-04-01
      • 2016-05-07
      • 2017-03-28
      • 2013-04-04
      • 2010-10-01
      相关资源
      最近更新 更多