-2

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]
Amro
  • 123,847
  • 25
  • 243
  • 454
  • 1
    Please provide some more details, and examples of what have you tried so far. – BartoszKP Aug 18 '13 at 00:02
  • What class are A, B, ...? Doubles, chars,...? Also, are they scalar? – Oleg Aug 18 '13 at 00:03
  • 1
    it looks like you are doing the *cartesian product* (although you are missing some combinations: ABG, EFC). See this: http://stackoverflow.com/questions/4165859/matlab-generate-all-possible-combinations-of-the-elements-of-some-vectors – Amro Aug 18 '13 at 00:06
  • here is another related question: [MATLAB: Combinations of an arbitrary number of cell arrays](http://stackoverflow.com/q/8492277/97160) – Amro Aug 18 '13 at 01:23
  • From the example it's hard to tell what you want. You should explain – Luis Mendo Aug 18 '13 at 03:03

1 Answers1

1

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'
Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454