MATLAB: Combinations of an arbitrary number of cell arrays

前端 未结 2 500
囚心锁ツ
囚心锁ツ 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'
    

提交回复
热议问题