Generate a matrix containing all combinations of elements taken from n vectors

后端 未结 4 1480
孤街浪徒
孤街浪徒 2020-11-21 11:52

This question pops up quite often in one form or another (see for example here or here). So I thought I\'d present it in a general form, and provide an answer which might se

4条回答
  •  無奈伤痛
    2020-11-21 12:19

    A little bit simpler ... if you have the Neural Network toolbox you can simply use combvec:

    vectors = {[1 2], [3 6 9], [10 20]};
    combs = combvec(vectors{:}).' % Use cells as arguments
    

    which returns a matrix in a slightly different order:

    combs =
    
         1     3    10
         2     3    10
         1     6    10
         2     6    10
         1     9    10
         2     9    10
         1     3    20
         2     3    20
         1     6    20
         2     6    20
         1     9    20
         2     9    20
    

    If you want the matrix that is in the question, you can use sortrows:

    combs = sortrows(combvec(vectors{:}).')
    % Or equivalently as per @LuisMendo in the comments: 
    % combs = fliplr(combvec(vectors{end:-1:1}).') 
    

    which gives

    combs =
    
         1     3    10
         1     3    20
         1     6    10
         1     6    20
         1     9    10
         1     9    20
         2     3    10
         2     3    20
         2     6    10
         2     6    20
         2     9    10
         2     9    20
    

    If you look at the internals of combvec (type edit combvec in the command window), you'll see that it uses different code than @LuisMendo's answer. I can't say which is more efficient overall.

    If you happen to have a matrix whose rows are akin to the earlier cell array you can use:

    vectors = [1 2;3 6;10 20];
    vectors = num2cell(vectors,2);
    combs = sortrows(combvec(vectors{:}).')
    

提交回复
热议问题