我想从两个字符串数组中获取所有可能的组合。例如,如果'
a = ['Hello', 'World']
b = ['Hey', 'Earth']
我要输出
c = ['Hello','Hey';...
'Hello','Earth';...
'World,'Hey';...
'World,'Earth']
答案 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
,但是效率较低,因为它通过计算A
,B
以及将它们组合以创建时都计算和存储网格值数组C
:
[A,B] = ndgrid(a,b);
C = [A(:) B(:)];