-1

I am looking for a method of generating a matrix that contains all the combinations of vectors in MATLAB, like below

>> combvec(1:3,2:4)

ans =

     1     2     3     1     2     3     1     2     3
     2     2     2     3     3     3     4     4     4

As we can see, the example above is given two vectors, i.e., 1:3 and 2:4. However, if we have a variable number of vectors, e.g., v1,v2,...vn (where n is not given), then how can we generate all combinations?

For instance, given v1,v2,...vn, is there any way of generating the same result as combvec(v1,v2,...vn) but without writting down all n vectors (since n might be a large number and varying each time)?

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81

1 Answers1

1

You can unpack a cell with mycell{:}, if passed as an argument; each element of the cell will be interpreted as a new argument:

v1 = [1,2,3];
v2 = [2,3,4];
v3 = [3,4,5];

% We put everything in a cell
v = {v1,v2,v3};

% We unpack our cell into combvec
combvec(v{:})

Of course this example is pretty useless, but in a real case situation you can simply store your vectors directly in a cell v{ii} = ...

obchardon
  • 10,614
  • 1
  • 17
  • 33