如何在不重复的情况下获取数组元素的所有可能组合

发布于 2025-01-24 17:01:40 字数 169 浏览 1 评论 0原文

我有字符串元素的向量vector = {'a','b','c'}
我想生成数组的三个元素的所有可能组合,但没有重复。
我期望以下结果:{'a','b','c','ab','ac','bc','abc'}
我该如何在MATLAB中这样做?

I have a vector of string elements vector = {'A','B','C'}.
I want to generate all possible combination of the three elements of the array but without duplicate.
I expect the following result: {'A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC'}.
How can I do that in MATLAB?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咽泪装欢 2025-01-31 17:01:40

从所需的结果来看,您希望使用'a'''''的2个选择的所有组合代码>''(没有)。您可以使用 nchoosek 遵循

result = nchoosek(' ABC', 2) % note space for empty

输出

result =
  6×2 char array
    ' A'
    ' B'
    ' C'
    'AB'
    'AC'
    'BC'

然后删除空间并将组合转换为单元格数组:

result = strrep(cellstr(result), ' ', '')

正如沃尔夫(Wolfie)指出的那样,这仅适用于单个字符输入,对于多字符输入,我们可以使用字符串数组而不是char数组:

result = nchoosek(["","A1","B2","C3"], 2);
result = result(:,1) +  result(:,2) % string cat
% result = cellstr(result); % optional if want cell output
result = 
  6×1 string array
    "A1"
    "B2"
    "C3"
    "A1B2"
    "A1C3"
    "B2C3"

Judging from your desired result, you want all the combinations with 2 choices of 'A', 'B', 'C', and '' (nothing). You can do it with nchoosek as follows

result = nchoosek(' ABC', 2) % note space for empty

Output

result =
  6×2 char array
    ' A'
    ' B'
    ' C'
    'AB'
    'AC'
    'BC'

Then removing the spaces and converting the combinations to a cell array:

result = strrep(cellstr(result), ' ', '')

As Wolfie pointed out, this only works for single character input, for multi character inputs we can use string arrays instead of char arrays:

result = nchoosek(["","A1","B2","C3"], 2);
result = result(:,1) +  result(:,2) % string cat
% result = cellstr(result); % optional if want cell output
result = 
  6×1 string array
    "A1"
    "B2"
    "C3"
    "A1B2"
    "A1C3"
    "B2C3"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文