如何为每种可能的组合组合2个字符串数组

时间:2019-04-22 20:13:03

标签: matlab

我想从两个字符串数组中获取所有可能的组合。例如,如果'

a = ['Hello', 'World']
b = ['Hey', 'Earth']

我要输出

c = ['Hello','Hey';...
     'Hello','Earth';...
     'World,'Hey';...
     'World,'Earth']

1 个答案:

答案 0 :(得分:0)

首先,这不是string数组,而是char数组。要成为字符串数组,需要用引号",所以要用a = ["Hello", "World"];

要进行合并,只需执行两次循环:

a = ["Hello", "World"];
b = ["Hey", "Earth"];

rowNumber = length(a) * length(b);

C = strings(rowNumber,2);
rowCounter = 0;
for i=1:length(a)
    for j=1:length(b)
        rowCounter = rowCounter + 1;
        C(rowCounter,1) = a(i);
        C(rowCounter,2) = b(j);
    end
end

您可以尝试使用ndgrid,但是效率较低,因为它通过计算AB以及将它们组合以创建时都计算和存储网格值数组C

[A,B] = ndgrid(a,b);
C = [A(:) B(:)];