MATLAB Answers

How can I obtain all possible combinations of given vectors in MATLAB?

1,048 views (last 30 days)
I want to obtain all possible combinations of a set of vectors. For example, if
a=1:3; b=4:5
I want to generate the following vector:
C=[1 4;...
1 5;...
2 4;...
2 5;...
3 4;...
3 5]

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 2 Aug 2017
There are several ways to obtain all possible combinations of a set of vectors.
a) If the set consists of 2 vectors, a and b, you can execute the following code:
 
[A,B] = meshgrid(a,b);
c=cat(2,A',B');
d=reshape(c,[],2);
b) If the set consists of 2 or more vectors, you can use the Neural Network Toolbox function COMBVEC to achieve the desired result. More information about COMBVEC function can be obtained form the following link:
c) If Neural Network Toolbox is not available, you can achieve the desired result from MATLAB Central file exchange* function through the following link:
*Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.
  2 Comments
Abhilash
Abhilash on 30 Apr 2021
I used allcomb and your tip and it works perfectly and so fast! Thank you!

Sign in to comment.

More Answers (3)

stewpend0us
stewpend0us on 30 Jan 2017
This worked for me (probably the same thing that's going on in the "ALLCOMB" function that was suggested):
elements = {1:2, 3:5, 6:7, 8:10}; %cell array with N vectors to combine
combinations = cell(1, numel(elements)); %set up the varargout result
[combinations{:}] = ndgrid(elements{:});
combinations = cellfun(@(x) x(:), combinations,'uniformoutput',false); %there may be a better way to do this
result = [combinations{:}]; % NumberOfCombinations by N matrix. Each row is unique.
  3 Comments

Sign in to comment.


Jingjing Xu
Jingjing Xu on 26 Jan 2021
Edited: Jingjing Xu on 27 Jan 2021
I don't have the Neural Network Toolbox, because my laptop is running out of space. But, I figured out there's a way to do this by using ndgrid and reshape. (Edits: no need to use reshape, Adam below has a two-line code to achieve this goal.)
[A B C]=ndgrid(1:2,3:4,5:6);
A1=reshape(A,[],1);
B1=reshape(B,[],1);
C1=reshape(C,[],1);
d=[A1,B1,C1]
  8 Comments

Sign in to comment.


Akhil Shetty
Akhil Shetty on 13 Jan 2018
Hi... I was recently looking for the same thing... I managed to come up with a piece of code which uses the 'combvec' instruction in Matlab.
no_inp=3 % number of inputs we want...in this case we have 3 inputs (a,b,c). a=[1 2 3] b=[1 2 3] c=[1 2 3]
pre_final=combvec(c,b,a)';
final=zeros(size(pre_final));
for i=1:no_inp
final(:,i)=pre_final(:,no_inp-i+1);
end
final
Hope it helps. Good luck.

Products


Release

R2007b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!