# combinations with 2 columns

16 views (last 30 days)
sampath kumar punna on 18 Oct 2019
Answered: Jos (10584) on 21 Oct 2019
Hi guys can you help out in creating a combination
if we got 2 columns and 3 rows
1 2
1 2
1 2
Combination 1: 1,1,1
Combination 2: 1,1,2
Combination 3: 1,2,1
Combination 4:2,1,1
Combination 6: 2,2,2
Combination 7: 2,2,1
Combination 8: 2,1,2
Combination 9: 1,2,2

Athul Prakash on 21 Oct 2019
Hi Sampath,
Look like you want to select exactly 1 element per row, from among all columns of the matrix. Hence, if there are m rows and n elements per row (or n columns), there would be n^m combinations generated (2^3 = 8 in your question).
Solution using combvec()
If we give row vectors as inputs to combvec(), it generates all possible combinations of elements from those row vectors. Hence, we may pass each row to combvec() as a separate argument, as illustrated below:
mat = [1 2; 1 2; 1 2];
ans = combvec(mat(1,:), mat(2,:), mat(3,:)) % Each column of 'ans' is one of your desired combinations
If the number of rows is not known, you may want to use a for loop:
% suppose 'mat' contains the data
num_rows = size(mat,1);
combs = mat(1,:);
for i=2:num_rows
combs = combvec(mat(i,:), combs);
end
disp(combs);
Hope it Helps!

Andrei Bobrov on 21 Oct 2019
Combination = fullfact([2 2 2]);

Jos (10584) on 21 Oct 2019
Take a look at ALLCOMB on the File Exchange:
X = [1 2 ; 3 4 ; 5 6] ; % input matrix
[n, m] = size(X) % [n m]
C = mat2cell(X, ones(1,n), m)
B = allcomb(C{:})