0

I want to obtain all possible combinations from two string arrays. For example if'

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

I want to output

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

1 Answers1

0

Firstly, this is not a string array, it is a char array. To be a string array you need the quotes ", so a = ["Hello", "World"];.

For combining, just do a double loop:

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

As an alternative, you could try the ndgrid, but this is less efficient since it computes and stores the grid values both by computing A, B and when combining them to create the array C:

[A,B] = ndgrid(a,b);
C = [A(:) B(:)];
tryman
  • 3,233
  • 1
  • 12
  • 23