1,048 views (last 30 days)

Show older comments

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]

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.

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.

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]

Walter Roberson
on 10 Aug 2021

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.

Adam Danz
on 27 Jan 2021

Your solution can be condensed into 1 line, below.

final = fliplr(combvec(c,b,a)');

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

Start Hunting!