MATLAB: Combinations of an arbitrary number of cell arrays

前端 未结 2 499
囚心锁ツ
囚心锁ツ 2020-12-11 06:57

Is there a command or one-line strategy in MATLAB that will return all the combinations of the components of n cell arrays, taken n at a time?

相关标签:
2条回答
  • 2020-12-11 07:09

    Although I address this in my answer to a related/near duplicate question, I'm posting a different version of my solution here since it appears you want a generalized solution, and my other answer is specific for the case of three input sets. Here's a function that should do what you want for any number of cell array inputs:

    function combMat = allcombs(varargin)
      sizeVec = cellfun('prodofsize', varargin);
      indices = fliplr(arrayfun(@(n) {1:n}, sizeVec));
      [indices{:}] = ndgrid(indices{:});
      combMat = cellfun(@(c,i) {reshape(c(i(:)), [], 1)}, ...
                        varargin, fliplr(indices));
      combMat = [combMat{:}];
    end
    

    And here's how you would call it:

    >> combMat = allcombs(A, B)
    
    combMat = 
    
        'a1'    'b1'
        'a1'    'b2'
        'a1'    'b3'
        'a2'    'b1'
        'a2'    'b2'
        'a2'    'b3'
    
    0 讨论(0)
  • 2020-12-11 07:11

    A 2-line strategy:

     A = {'a1','a2'};
     B = {'b1','b2','b3'};
    
    [a b]=ndgrid(1:numel(A),1:numel(B));
    C= [A(a(:))' B(b(:))']
    
    C = 
        'a1'    'b1'
        'a2'    'b1'
        'a1'    'b2'
        'a2'    'b2'
        'a1'    'b3'
        'a2'    'b3'
    
    0 讨论(0)
提交回复
热议问题