0

I have three cell arrays of strings and I want to find all possible combinations of the three. So if I have:

One=      Two=      Three=
[A B      [M N      [W X
 C D]      O P]      Y Z]

I want to be able to find all combinations, which would give me something like:

Four=
[AMW AMX AMY AMZ ANW ANX ANY ANZ AOW AOX AOY AOZ APW APX APY APZ
 BMW BMX BMY BMZ BNW BNX BNY BNZ BOW BOX BOY BOZ BPW BPX BPY BPZ
 etc.
 etc.]

Is there a simple way to do this or will I have to somehow change the strings to integer values?

Jana Smith
  • 27
  • 5
  • 1
    _If your strings are always single letters_ (as in your example), you can (1) define `One = 'ABCD'; Two = 'MNOP'; Three = 'WXYZ';`(2) Apply [this answer](http://stackoverflow.com/a/21895344/2586922) to `vectors = {One, Two, Three};` (3) If needed, convert the result `combs = cellstr(combs);` – Luis Mendo Dec 07 '15 at 01:28

1 Answers1

1

So, you have three cell arrays:

One = {'A' 'B' 'C' 'D'};
Two = {'M' 'N' 'O' 'P'};
Three = {'W' 'X' 'Y' 'Z'};

We can try to work with their indices

a = 1:length(One);
ind = combvec(a,a,a);

ind would be the matrix with all the combinations of three numbers from 1 to 4, e.g. 111 112 113 114 211 212 213 214 etc. According to combinatorics, its dimensions would be 3x64. The indices correspond to the letters in your cell array, i.e. 214 would correspond to 'BMZ' combination.

EDIT, developed an easy way to generate the combinations without combvec with help of @LuisMendo 's answer:

a=1:4;
[A,B,C] = ndgrid(a,a,a);
ind = [A(:),B(:),C(:)]';

Then you create the blank cell array with length equal to 64 - that's how many combinations of three letters you are expected to get. Finally, you start a loop that concatenates the letters according to the combination in ind array:

Four = cell(1,length(ind(1,:)));
for i = 1:length(ind(1,:))
    Four(i) = strcat(One(ind(1,i)),Two(ind(2,i)),Three(ind(3,i)));
end

So, you obtain:

Four = 

'AMW'    'BMW'    'CMW'    'DMW'    'ANW'    ...
brainkz
  • 1,335
  • 10
  • 16