0

I need to combine all data of n (random) arrays with different lengths. ex: a=[1 3 2 7 8], b=[2 5 3 9] and c=[5 6] and maybe we have d, e, f etc.... I need the combination of all elements like: M={[1 2 5], [1 2 6], [1 5 5], [1 5 6], [1 3 5], [1 3 6] ....}.

mona
  • 101
  • 6

1 Answers1

1

Solution for 3 arrays:

[A,B,C] = meshgrid(a, b, c);
M = [A(:), B(:), C(:)];

Solution for n arrays iterating over the short dimension n:

a=[1 3 2 7 8];
b=[2 5 3 9];
c=[5 6];
d=[1 3 5];

arrays = { a, b, c, d };
M = a';

for i = 2:length(arrays)
    A1 = M;
    A2 = arrays{i}';
    [i1, i2] = meshgrid(1:length(A1), 1:length(A2));
    M = [A1(i1(:), :) A2(i2(:))];    
end
Iban Cereijo
  • 1,675
  • 1
  • 15
  • 28