Combination of special sets and subsets

조회 수: 2 (최근 30일)
hassan
hassan 2014년 5월 1일
답변: Geoff Hayes 2014년 5월 1일
Hi
I am having trouble in solving a combination problem as follows, For example:
There are 4 sets each having different sub parts
set(A) = ['A1' 'A2' 'A3' 'A4' 'A5' 'A6']; set(B) = ['B1' 'B2' 'B3' 'B4' 'B5']; set(C) = ['C1' 'C2' 'C3' 'C4']; set(D) = ['D1' 'D2' 'D3' 'D4']; Based original code of combination:
combos = combntns(set,subset); now the question is: I have sub part of sets and I want combination of subparts of sets for subset=4 ,where same sub parts of a set should not be in the same combination. The problem is that by running original code, sub parts of single set also is getting combined, but this is not the right for me. the result should be as follow:
['A1' 'B1' 'C1' 'D1'], ['A1' 'B2' 'C1' 'D1'], ['A1' 'B3' 'C1' 'D1'], ['A2' 'B1' 'C1' 'D3'], ['A3' 'B3' 'C2' 'D3'], ['A5' 'B5' 'C4' 'D2'], ... AND GO ON..... but original code creates this: [A1 A2 C1 D1], or [A1 B1 B2 D1], ..... which is not true because sub part of set is repeated in single combination (for example B1 and B2 in the same combination).
i would appreciate if someone can put me through right direction.
Regards

답변 (1개)

Geoff Hayes
Geoff Hayes 2014년 5월 1일
Hi hassan,
My understanding of your question is that you want a way to find all combinations/sets of four elements where each set has exactly one element from (super) sets A, B, C, and D. Given the sizes of sets A through D, then I expect there to be 6*5*4*4=480 different subsets. Probably the easiest way to do this (and not necessarily the most efficient) is to have four loops, one within the other, and combine all possible sets:
next=1;
for i=1:length(A)
for j=1:length(B)
for k=1:length(C)
for m=1:length(D)
allcombos(next) = ???; % some combination of the data in A,B,C,and D
next=next+1;
end
end
end
end
The above is just an example - allcombos could be a cell array or a matrix of 480 rows by whatever number of columns, it all depends on how you want to store the data. A fancier solution would be to recurse on a subset of the data and concatenate sets as you go. This would probably allow more flexibility especially if your requirement changes to say only choose three elements from the four sets of data.
Geoff

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by