All possible combination for picking up from arrays

조회 수: 2 (최근 30일)
joy
joy 2014년 10월 14일
댓글: Guillaume 2014년 10월 14일
I have 3 arrays namely a,b & c.
Now I have total 10 elements..a has 5 elements, b has 2 and c has 3, all elements in an array are identical.
I have to pick up 4 elements in all possible distinct combination from these arrays, like I can pick up all 4 from array a, again 3 from array a and 1 from array b , 2 from each array b & c and so on.
How to write this logic in matlab so that all possible combination is covered.

채택된 답변

Guillaume
Guillaume 2014년 10월 14일
편집: Guillaume 2014년 10월 14일
One simple way that may be a bit wasteful as it calculate more combinations than necessary and remove redundant ones:
Concatenate your 3 arrays and use nchoosek to pick all combinations of 4 elements from that concatenation. Remove duplicate combinations using unique (with the 'rows' option).
With only ten elements it's near instananeous anyway. With moderately more elements, nchoosek will take too long and generate too many combinations, so a different method will have to be used.
  댓글 수: 2
joy
joy 2014년 10월 14일
Actually elements in the array are identical. so let array a contains 5 elements say a=[1,2,3,4,5]; now, If I select 1,2,3,4 or 2,3,4,5 it doesn't matter.
Guillaume
Guillaume 2014년 10월 14일
Yes, I understood that the elements are identical. That's why you use unique to remove the combinations where the same number of elements have been picked from each array:
a = [1 1 1 1 1];
b = [2 2];
c = [3 3 3];
abc = [a b c];
allcombs = nchoosek(abc, 4);
combs = unique(allcombs, 'rows')

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by