Question

Say, I have two vectors [A B C] and [E F G]

Now, I want a matrix like this below:

[A B C; E F G ;  A F G; A F C; E B C; E B G]
Was it helpful?

Solution

Here is the same code I mentioned for Cartesian product, adapted to work on sets of strings instead of numeric data:

sets = {{'A' 'E'};   % first position
        {'B' 'F'};   % second position
        {'C' 'G'}};  % third position

[val,~,idx] = cellfun(@unique, sets, 'Uniform',false);
indices = cell(numel(idx),1);
[indices{:}] = ndgrid(idx{:});
cartProd = cellfun(@(ind,v) v(ind(:)), indices, val, 'Uniform',false);
cartProd = vertcat(cartProd{:})';

This will work for any number of sets, each with any number of elements.

The resulting combinations for the example above (one per row):

>> cartProd
cartProd = 
    'A'    'B'    'C'
    'E'    'B'    'C'
    'A'    'F'    'C'
    'E'    'F'    'C'
    'A'    'B'    'G'
    'E'    'B'    'G'
    'A'    'F'    'G'
    'E'    'F'    'G'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top