1

I have several vectors or lists of vectors and would like to make up all possible concatenations of their entries. Here is an example:

a1=4;
a2=[1,6;1,9;6,9];
a3=[2;7];

That all should result in:

[4,1,6,2]
[4,1,6,7]
[4,1,9,2]
[4,1,9,7]
[4,6,9,2]
[4,6,9,7]

I think my question is similar to this one: Generate all possible combinations of the elements of some vectors (Cartesian product) but I am not really able to adapt the answers to my problem.

EDIT: Thank you again for the answer and corrections! As beaker already said its works like a charm in octave. Now I would also like to have it a little more flexible for an arbitrary number of a's combined in a cell array (or any other structure which would fit the potential solution better). I made a work around with composing a string and then evaling it. But that does not seem pretty elegant to me. Is it possible to have it more... algorithmic?

Community
  • 1
  • 1
milkpirate
  • 267
  • 1
  • 18

1 Answers1

3

I am answering using MATLAB in the hope that the same code works in Octave as well.


Here's a solution based on Amro's answer in the question you linked:

a1=4;
a2=[1,6;1,9;6,9];
a3=[2;7];

nRows = [size(a1,1), size(a2,1), size(a3,1)];

[x,y,z] = ndgrid(1:nRows(1),1:(nRows(2)),1:(nRows(3)));
cartProd = [a1(x(:),:) a2(y(:),:) a3(z(:),:)];

Which results in:

cartProd =

     4     1     6     2
     4     1     9     2
     4     6     9     2
     4     1     6     7
     4     1     9     7
     4     6     9     7

It's a slightly different order than what you showed, but I think it could still be useful to you.

Community
  • 1
  • 1
Dev-iL
  • 23,742
  • 7
  • 57
  • 99