'How to get all possible combinations of array elements without duplicate

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?



Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1