playcode
playcode

Reputation: 31

How can I create all combinations of characters in sets of text?

For example, I have sets of text like so:

Column 1:

a
b

Column 2:

l
m
n

Column 3 :

v
w
x
y

And I want to combine them to get an output like this:

alv
alw
alx
aly
amv
amw
amx
amy
...

Which will output 24 combinations of text. If I were to only use the first two columns, it will output 2*3=6 combinations.

I'm not able to figure out how to do this in MATLAB. Any suggestions?

Upvotes: 3

Views: 2078

Answers (1)

gnovice
gnovice

Reputation: 125864

One solution is to use the function NDGRID to generate all of the combinations of indices into your sets:

C = {'ab' 'lmn' 'vwxy'};            %# Cell array of text sets
sizeVec = cellfun('prodofsize',C);  %# Vector of set sizes
[index3,index2,index1] = ndgrid(1:sizeVec(3),...  %# Create all the index
                                1:sizeVec(2),...  %#   combinations for
                                1:sizeVec(1));    %#   the sets
combMat = [C{1}(index1(:)); ...  %# Index each corresponding cell of C and
           C{2}(index2(:)); ...  %#   concatenate the results into one matrix
           C{3}(index3(:))].';

And you should get the following for combMat:

alv
alw
alx
aly
amv
amw
amx
amy
anv
anw
anx
any
blv
blw
blx
bly
bmv
bmw
bmx
bmy
bnv
bnw
bnx
bny

If you just want to get combinations for columns 1 and 2, remove the first input and output arguments from the call to NDGRID and remove C{3}(index3(:)) from the computation of combMat.

If you instead want C to be a cell array of cell arrays of strings instead of a cell array of character arrays, you can still use the exact same code above. The only difference will be that combMat will end up being a cell array of strings instead of a character array.

UPDATE:

I've actually created a generalized solution that can compute combinations for any number of sets (either character arrays or cell arrays of strings). You can find it in this answer to a closely-related question. To reproduce the above example, you would call it like so:

combMat = allcombs(C{:});

Upvotes: 3

Related Questions