combinations with 2 columns

조회 수: 13 (최근 30일)
sampath kumar punna
sampath kumar punna 2019년 10월 18일
답변: Jos (10584) 2019년 10월 21일
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

답변 (3개)

Athul Prakash
Athul Prakash 2019년 10월 21일
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()
Please read up on combvec here:
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
Andrei Bobrov 2019년 10월 21일
Combination = fullfact([2 2 2]);

Jos (10584)
Jos (10584) 2019년 10월 21일
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{:})

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by