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
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.
Nasser Hakami
Nasser Hakami 2019 年 11 月 18 日
thanks. however i couldn't manage to do it

サインインしてコメントする。

 採用された回答

the cyclist
the cyclist 2019 年 11 月 16 日

0 投票

I would download John D'Errico's partitions function, and then I believe your answer is
p = partitions(15,[1 1 1 1])

5 件のコメント

Nasser Hakami
Nasser Hakami 2019 年 11 月 18 日
tahnks. It look great code. but i coulnt mange to run correctly. i will try again to adapt it
the cyclist
the cyclist 2019 年 11 月 18 日
Do you mean that the code will not work for you, or that you do not get the result you expect?
(FYI, Walter's solution and this one give the same result.)
Nasser Hakami
Nasser Hakami 2019 年 11 月 18 日
編集済み: the cyclist 2019 年 11 月 18 日
first tahnks for your feedback
to answer you: i could not mange to run the code
i will try to make exampele easier
4 apples, 2 person. so ALL combinations are
[0 4
1 3
2 2
3 1
4 0]
if 4 apples , 3 persons. combination are
[0 0 4
0 1 3
0 2 2
0 3 1
0 4 0
1 0 3
1 1 2
1 2 1
1 3 0
2 0 2
2 1 1
2 2 0
3 0 1
3 1 0
4 0 0]
the cyclist
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
Nasser Hakami
Nasser Hakami 2019 年 11 月 19 日
thanks a lot
it is working perfect
the problem that i just copied the code from webpage and i didnt download file

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 11 月 18 日

0 投票

[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);

カテゴリ

Community Treasure Hunt

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

Start Hunting!

Translated by