Editor's Note: This file was a File Exchange Pick of the Week
ALLCOMB  All combinations
B = ALLCOMB(A1,A2,A3,...,AN) returns all combinations of the elements
in the arrays A1, A2, ..., and AN. B is PbyN matrix, where P is the product
of the number of elements of the N inputs. This functionality is also
known as the Cartesian Product. The arguments can be numerical and/or
characters, or they can be cell arrays.
Examples:
allcomb([1 3 5],[3 8],[0 1]) % numerical input:
% > [ 1 3 0
% 1 3 1
% 1 8 0
% ...
% 5 3 1
% 5 8 1 ] ; % a 12by3 array
allcomb('abc','XY') % character arrays
% > [ aX ; aY ; bX ; bY ; cX ; cY] % a 6by2 character array
allcomb('xy',[65 66]) % a combination
% > ['xA' ; 'xB' ; 'yA' ; 'yB'] % a 4by2 character array
allcomb({'hello','Bye'},{'Joe', 10:12},{99999 []}) % all cell arrays
% > { 'hello' 'Joe' [99999]
% 'hello' 'Joe' []
% 'hello' [1x3 double] [99999]
% 'hello' [1x3 double] []
% 'Bye' 'Joe' [99999]
% 'Bye' 'Joe' []
% 'Bye' [1x3 double] [99999]
% 'Bye' [1x3 double] [] } ; % a 8by3 cell array
ALLCOMB(..., 'matlab') causes the first column to change fastest which
is consistent with matlab indexing. Example:
allcomb(1:2,3:4,5:6,'matlab')
% > [ 1 3 5 ; 1 4 5 ; 1 3 6 ; ... ; 2 4 6 ]
If one of the arguments is empty, ALLCOMB returns a 0byN empty array.
See also nchoosek, perms, ndgrid
and nchoose, combn, kthcombn (matlab Central FEX)
Jos (10584) (2020). allcomb(varargin) (https://www.mathworks.com/matlabcentral/fileexchange/10064allcombvarargin), MATLAB Central File Exchange. Retrieved .
4.2.0.0  fixed some grammar mistakes 

4.1.0.0  fixed error noted by Richard 

1.6.0.0  v4.0 accepts cell arrays as input 

1.5.0.0  now accepts character arrays 

1.4.0.0  remove superfluous line of code (thanks to Edward) 

1.3.0.0  (2.1, feb 2011)  fixed the check of the last argument when the last argument was neither a char or a double. 

1.2.0.0  Convinced by Bruno, I decided to change the behavior when an input is empty (now returns empty instead of ignoring the input). 

1.1.0.0  little speed improvement as suggested by Jan Simon 

1.0.0.0  1) Removed a erroneous warning when no empty inputs were _not_ provided.


Too hasty in my first revision ... 
Inspired: Create Unique Interaction Variables
Create scripts with code, output, and formatted text in a single executable document.
I recently upgraded MATLAB to R2020a, and this function now causes errors. It works well in R2019b. Does anyone know how to fix?
Error using repmat
Requested (xx GB) array exceeds maximum array size preference. Creation of arrays greater than this limit may
take a long time and cause MATLAB to become unresponsive.
Error in ndgrid (line 72)
varargout{i} = repmat(x,s);
Error in allcomb (line 109)
[A{ii}] = ndgrid(args{ii}) ;
How is this functionality not part of the base MATLAB? Thanks for contributing.
@mehdi J: most likely you made a mistake in your code. ALLCOMB expects 1 or more input arguments, as described in the help
hi,I have faced with this E:
Error using allcomb (line 66)
Not enough input arguments.
how could I fix it???
A highlight of MATLAB FEX: neatly written, clear code, excellent help and explanation.
Easy to use, reliable, and indispensable when the need arises: thank you Jos!
@Mendi Barel: You can use simple commaseparated list expansion for this:
C = {[1 2],[1 2 3],[5 6]})
allcomb(C{:})
Great. Better to add support for dynamic size pf vectors. For example this kind of input:
allcomb({[1 2],[1 2 3],[5 6]})
Hello everybody, I have submitted a question regarding this function at Matlab's question section. Please feel free to have a look at: https://uk.mathworks.com/matlabcentral/answers/325965erroneousinputintotheallcombfunction
I am having trouble with the input.
Sincerely,
Christoffer
@shiva, can you explain better your position about the memory?
This is like combntns, very useful. I don't know why matlab developer removed it from the library.
Thanks!
Greatings
@midhun does this solve your needs?
http://de.mathworks.com/help/matlab/matlab_prog/findarrayelementsthatmeetacondition.html
Is it possible to set a constraint. I mean each combination in A should satisfy a condition. If
A= 0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
0 3
1 3
2 3
Then I need only a combination that satisfies
B*A'=constant (for some matrix B).
If I generate all combination for 20 vectors using combvec, I am getting around 400,000 combinations, But I need only 200 of them which satisfies my condition.
Is it possible to pass a matrix as input argument to allcomb so that the input arguments are columns of matrix?...
Is it possible to set a constraint. I mean each combination in A should satisfy a condition. If
A= 0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
0 3
1 3
2 3
Then I need only a combination that satisfies
B*A'=constant (for some matrix B).
If I generate all combination for 20 vectors using combvec, I am getting around 400,000 combinations, But I need only 200 of them which satisfies my condition.
To make allcomb work with cell inputs and 'matlab' parameter, you need to add the line:
varargin(end)=[];
after the if statement (line 69)
Richard
@Alexander Implementing this would require the Statistics Toolbox. However, you can easily generate the table yourself, using ALLCOMB on the indices. I assume you should be able to do something like this:
idxAB = allcomb(1:numel(A),1:numel(B))
out = [A(idxAB(:,1)) B(idxAB(:,2))]
Excellent function! Given that this function can be used to create combinations of selections from a number of categories (A1...AN), could you allow it to operate on categorical arrays? The output could be either a table (preferably) or cell array, as in the example below.
A = categorical({'A1','A2'})
B = categorical({'B1','B2','B3'})
allcomb2(A,B)
% > Var1 Var2
% ____ ____
%
% A1 B1
% A1 B2
% A1 B3
% A2 B1
% A2 B2
% A2 B3
This is an awesome piece of code!
Although i have an request, like say when I have a 5 or more large vectors (eg.,200:200) i encounter memory problems.
I was thinking like,
1) check the maximum variable size for the particular computer.
2) if the size of the generated variable is more than the maximum size permitted store the intermediate result in a "mat" file. clear the contents of the variable and append the successive results to the end of the "mat" file
Hello,
I wanted to have the index of the computed combinaison.
I propose this solution if other people id interested:
[A index] = allcomb(varargin)
...
...
if nargout>1
create_index = @(x) cellfun(@(y) 1:numel(y), x, 'UniformOutput', false);
idx = create_index(args);
[index{ii}] = ndgrid(idx{ii});
index = reshape(cat(ni+1,index{:}),[],ni) ;
end
superb, i was trying for this problem, but this Ans solved my problem within second
@Ofer To combine strings with doubles you can use a cell array. You can use allcomb to retrieve the indices, as in
D = [10 11] % doubles
S = {'s1','s2','s3'}
ix = allcomb(1:numel(D), 1:numel(S))
great function. how can i combine strings with doubles?
@Amri, good suggestion! I will update the file shortly.
it works only with double variables !?
i need the same function but with caracters ?
Why not built in to Matlab?
Thanks Edward, a small glitch on my side ... fixed in version 2.2
Jos, I think you're missing a semicolon in line 60 for ischar(argn). Results in 0 being printed in the terminal without this.
Great and easy to use!
Can you explain how to install this and get it to work?
In the Neural Network Toolbox there is combvec, which produces the same results as the examples.
combvec([1 3 5],[3 8],[0 1])
combvec(1:2,3:4,5:6)
If you have the toolbox the combvec might be helpful, if not then allcomb might help for general.
Very efficient in my case.
Here is a debate that will convince you Jos.
A cartesian's product of n sets has a cardinal equals to the product of cardinals of each set.
NCOMB must return [prod(numel(xi)) x n] size array.
An empty set has zeros cardinal, thus all comb MUST return 0 x n.
This is a correct answer.
Why this is important. Here is an example
In post #4 of this thread
http://www.mathworks.com/matlabcentral/newsreader/view_thread/299532
I used NDGRID to generate a combination of 2 sets. NDGRID handles correctly empty configuration, this my code can directly work. I can't replace with ALLCOMB because the empty set is not consistently handle.
Somehow my first reply to Bruno does not show up. I wanted to say to Bruno "maybe I can issue a warning when an input is empty".
If ALLCOMB returns empty or ignores an empty input is, in my opinion, a matter of debate.
Hmm, there already is a warning ... I should read my own code more carefully ...
Jos, IMO allcomb returns incorrect result when one of the argument is is empty
It should return an empty (0xn) array where n is the number of arguments.
Very nice!
Comapct and fast algorithm  thanks!
The flipping can be omitted to save time:
[A{1:ni}] = ndgrid(args{ii}) ;
A = reshape(cat(ni+1,A{:}),[],ni) ;
A = A(:,ii) ;
==>
[A{ii}] = ndgrid(args{ii}) ;
A = reshape(cat(ni+1,A{:}),[],ni) ;
E.g. for ALLCOMB(1:100, 1:100, 1:100) this is 24% faster on my machine (Matlab 2009a, WinXP, 32 bit).
very useful. it is possible to have the exact same thing for symbolic objects (i am working with tomSym)?
so powerful, it is what I've been looking for~~
easy things are always the best! Great!
Thanks! I've been looking for something like this.
Good job
Great, just what I wanted!
where can I find allcomb.m file? Thanks!
nice function, poor not to find it in matlab itself ;)
I'd lost some time before I found it. This short piece of code sloves my problem and does it excellent. Thanks
Excellent! That's what I needed!
I just updated this file: a minor "bug" was removed when none of the inputs were empty. I also added the option to let the first argument move most rapidly, as suggested by John D'Errico.
Good help, error checks, not much to say here. Only one comment: I'd argue that the first argument should move most rapidly, to be consistent with Matlab indexing.