How to create all combinations of characters in typesets?

For example, I have sets of text, for example:

Column 1:

a
b

Column 2:

l
m
n

Column 3:

v
w
x
y

And I want to combine them to get this conclusion:

alv
alw
alx
aly
amv
amw
amx
amy
...

24 text combinations will be displayed. If I used only the first two columns, it would output 2 * 3 = 6 combinations.

I cannot figure out how to do this in MATLAB. Any suggestions?

+3
source share
1 answer

One solution is to use the NDGRID function to generate all index combinations in 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

1 2, NDGRID C{3}(index3(:)) combMat.

, C , . , combMat .

UPDATE:

, ( ). . , :

combMat = allcombs(C{:});
+3

All Articles