combination of integer numbers
조회 수: 2 (최근 30일)
이전 댓글 표시
I need to make distibution of 15 apples among 4 person [a b c d],
each person can have a value betwwen 0-15. and summation always (a+b+c+d=15)
so how can i generate the matrix for all possible combinantion
so i eapect matrix as
a = [1 14 0 0
0 0 0 15
3 6 2 4
...................
...................]
댓글 수: 2
Walter Roberson
2019년 11월 16일
One approach is to ndgrid() all possible combinations, and then check those to find the ones that add up to the right number.
채택된 답변
the cyclist
2019년 11월 16일
p = partitions(15,[1 1 1 1])
댓글 수: 5
the cyclist
2019년 11월 18일
I don't think an easier example was needed, but I can verify that
partitions(4,[1 1 1])
gives the same answer (not necessarily in the same row order).
I'm not sure why you couldn't run the code. Did you do the following?
- go to the link I uploaded
- click on the download button to get the files
- unzip the files
- put the partitions.m file in your path so that you can run it
추가 답변 (1개)
Walter Roberson
2019년 11월 18일
[Ag, Bg, Cg, Dg] = ndgrid(0:15);
Eg = [Ag(:), Bg(:), Cg(:), Dg(:)];
mask = sum(Eg,2) == 15;
selected = Eg(mask,:);
a = selected(:,1);
b = selected(:,2);
c = selected(:,3);
d = selected(:,4);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!