MATLAB: Enumerating All Combinations of Items in An Arbitrary Number of Sets [duplicate]
Possible Duplicate:
Matlab - Generate all possible combi开发者_如何学JAVAnations 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?
Try allcomb from the MATLAB file exchange
allcomb
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);
精彩评论