如何在文本集中创建所有字符组合?
例如,我有这样的文本集:
Column 1:
a
b
Column 2:
l
m
n
Column 3 :
v
w
x
y
我想将它们组合起来以获得如下输出:
alv
alw
alx
aly
amv
amw
amx
amy
...
这将输出 24 种文本组合。如果我只使用前两列,它将输出 2*3=6 个组合。
我不知道如何在 MATLAB 中执行此操作。有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是使用函数 NDGRID 生成所有组合集合中的索引数:
对于
combMat
,您应该得到以下结果:如果您只想获得第 1 列和第 2 列的组合,请从对 NDGRID 并删除
C{3}(index3(:)) 来自
combMat
的计算。如果您希望 C 成为字符串元胞数组的元胞数组,而不是字符数组的元胞数组,您仍然可以使用上面完全相同的代码。唯一的区别是combMat 最终将成为字符串元胞数组而不是字符数组。
更新:
我实际上创建了一个通用解决方案,可以计算任意数量的集合(字符数组或字符串元胞数组)的组合。您可以在此答案中找到密切相关的问题。要重现上面的示例,您可以像这样调用它:
One solution is to use the function NDGRID to generate all of the combinations of indices into your sets:
And you should get the following for
combMat
: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 ofcombMat
.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 thatcombMat
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: