如何在文本集中创建字符的所有组合? [英] How can I create all combinations of characters in sets of text?

查看:58
本文介绍了如何在文本集中创建字符的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一些类似的文本:

For example, I have sets of text like so:

第1列:

a
b

第2列:

l
m
n

第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
...

将输出24个文本组合.如果仅使用前两列,它将输出2 * 3 = 6个组合.

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

我无法弄清楚如何在MATLAB中执行此操作.有什么建议吗?

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

推荐答案

一种解决方案是使用 NDGRID 将所有索引组合生成到您的集合中:

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(:))].';

对于combMat,您应该获得以下信息:

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列的组合,请从对

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.

如果您想让C成为字符串单元格数组的单元格数组而不是字符数组的单元格数组,则仍然可以使用上面完全相同的代码.唯一的区别是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.

更新:

我实际上已经创建了一个通用的解决方案,该解决方案可以计算任意数量的集合(字符串的字符数组或单元格数组)的组合.您可以在

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{:});

这篇关于如何在文本集中创建字符的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆