在matlab中所有可能的组合和顺序中的每个字符串组之一的组合

时间:2015-02-18 08:46:05

标签: string matlab combinations permutation

所以我忘记了一个字符串,知道那里有三个子字符串,我知道每个字符串有几种可能性。所以我需要做的就是完成所有可能的组合和命令,直到找到我忘记的那个。但是,由于人类只能在working memory中保留四个项目(对我来说绝对是上限),我无法确定我检查过哪些项目。

所以说我有 n m 个字符串的集合,我怎样才能得到长度为 n 的所有字符串每个集合中的字符串是否按任何顺序?

我看到了一个如何在嵌套循环中执行此操作的示例,但我必须指定顺序。该示例适用于 n = 3 ,具有不同的 m 。不确定如何使this更通用:

first = {'Hoi','Hi','Hallo'}; 
second = {'Jij','You','Du'};
third = {'Daar','There','Da','LengthIsDifferent'}; 

for iF = 1:length(first) 
    for iS = 1:length(second)
        for iT = 1:length(third)
            [first{iF}, second{iS}, third{iT}] 
        end
    end 
end

关于this问题:它没有解决这个问题,因为它假定可供选择的集合的顺序是已知的。

1 个答案:

答案 0 :(得分:1)

这使用ndgrid生成索引的笛​​卡尔积。 然后使用一些cellfun - 魔法来获取所有字符串。然后它只是循环遍历所有排列并附加那些。

first = {'Hoi','Hi','Hallo'}; 
second = {'Jij','You','Du'};
third = {'Daar','There','Da','LengthIsDifferent'}; 
Vs = {first, second, third};
%% Create cartesian product
Indices = cellfun(@(X) 1:numel(X), Vs, 'uni', 0);
[cartesianProductInd{1:numel(Vs)}] = ndgrid(Indices{:});
AllStringCombinations = cellfun(@(A,I) A(I(:)), Vs, cartesianProductInd,'uni',0);
AllStringCombinations = cat(1, AllStringCombinations{:}).';%.'
%% Permute what we got
AllStringCombinationsPermuted = [];
permutations = perms(1:numel(Vs));
for i = 1:size(permutations,1)
    AllStringCombinationsPermuted = [AllStringCombinationsPermuted; ...
                                     AllStringCombinations(:,permutations(i,:));];
end