0

Possible Duplicate:
Matlab - Generate all possible combinations of the elements of some vectors

Say I have three sets:

A = [5 6 7]
B = [0 1]
C = [11 22 33]

I would like to create a MATLAB function that can take an arbitrary number of such sets and spit out all of their combinations. In the example above, it would spit out something along the lines of

[5 0 11
 5 0 22
 5 0 33
 5 1 11
 5 1 22 
 5 1 33
 ... 
 7 1 33]

The only way that I can think about doing something like this is by using nested for loops as folows:

output = zeros(length(A)*length(B)*length(C), 3)
row = 1

for i = 1:length(A)
     for j = 1:length(B)
         for k = 1:length(C)

         output(row,:) = [A(i) B(j) C(k)];
         row = row + 1;

         end
      end
end

Of course, this does not work without specifying the number of sets beforehand - so I'm wondering whether there is a simple fix or another smarter way around this problem?

Community
  • 1
  • 1
Berk U.
  • 7,018
  • 6
  • 44
  • 69

2 Answers2

2

Try allcomb from the MATLAB file exchange

allcomb

dave85
  • 303
  • 1
  • 7
1

Here is a quick function which will work if the inputs are a cell array.

function comb=allcomb(ip)

ncells=length(ip);
[nd{1:ncells}]=ndgrid(ip{:});
catted=cat(ncells,nd{1:ncells});
comb=reshape(catted,length(catted(:))/ncells,ncells);
mor22
  • 1,372
  • 1
  • 15
  • 32
  • basically does the same as @dave85's link. I'd written the code so I thought I'd post it. – mor22 Jul 07 '11 at 12:38