Generate all possible combinations of the elements of some vectors (Cartesian product)

后端 未结 4 1132
南笙
南笙 2020-11-22 13:32

I would like to generate all the possible combinations of the elements of a given number of vectors.

For example, for [1 2], [1 2] and

4条回答
  •  不要未来只要你来
    2020-11-22 13:49

    This late answers provides two additional solutions, where the second is the solution (in my opinion) and an improvement on Amro's answer solution with ndgrid by applying MATLAB's powerful comma-separated lists instead of cell arrays for high performance,

    1. If you have the Neural Network Toolbox: use combvec
    2. If you do not have the toolbox, as is usually the case: below is another way to generalize the Cartesian product for any number of sets.

    Just as Amro did in his answer, the comma-separated lists syntax (v{:}) supplies both the inputs and outputs of ndgrid. The difference (fourth line) is that it avoids cellfun and cell2mat by applying comma-separated lists, again, now as the inputs to cat:

    N = numel(a);
    v = cell(N,1);
    [v{:}] = ndgrid(a{:});
    res = reshape(cat(N+1,v{:}),[],N);
    

    The use of cat and reshape cuts execution time almost in half. This approach was demonstrated in my answer to an different question, and more formally by Luis Mendo.

提交回复
热议问题