Creating possible addition of a number

4 ビュー (過去 30 日間)
fyza affandi
fyza affandi 2019 年 2 月 24 日
コメント済み: fyza affandi 2019 年 2 月 24 日
I have a set of array A
A= [1 2 4 8 16]
For example I want a set of number that make up total of 4 (from A), it would be
B=[1 1 1 1] *total in array B would be 4*
B=[1 1 2]
B=[2 2]
B=[4]
Is it possible to do it in Matlab?
  1 件のコメント
Rik
Rik 2019 年 2 月 24 日
It is possible to this in Matlab. How would you try to solve it?

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

採用された回答

John D'Errico
John D'Errico 2019 年 2 月 24 日
編集済み: John D'Errico 2019 年 2 月 24 日
Trivial, if you download my partitions function from the File Exchange.
A = [1 2 4 8 16];
partitions(4,A)
ans =
4 0 0 0 0
2 1 0 0 0
0 2 0 0 0
0 0 1 0 0
Each row of the result tells you how many times that element appears in the target sum.
Find it here:
Note that the number of such partitions can be immense for some problems. You can easily overwhelm such a tool. For example, I have another utiility that will count the number of partitions of an integer.
numberOfPartitions(1000)
ans =
24061467864032622473692149727991
Thus as the sum of numbers in the set [1:1000]. It gets big, and does so pretty fast.

その他の回答 (1 件)

Stephen23
Stephen23 2019 年 2 月 24 日
Download John D'Errico's excellent partitions:
and use it like this:
>> A = [1,2,4,8,16];
>> M = partitions(4,A);
>> F = @(v)repelem(A,v);
>> C = cellfun(F,num2cell(M,2),'uni',0);
>> C{:}
ans =
1 1 1 1
ans =
1 1 2
ans =
2 2
ans =
4
  2 件のコメント
John D'Errico
John D'Errico 2019 年 2 月 24 日
One of the things I should have added as an option, was the ability to return the partitions in an expanded form, something much like Stephen did here. You can never have too many options in an interface. Well, at least not until you do. ;-)
fyza affandi
fyza affandi 2019 年 2 月 24 日
Thank you very much :)

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

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by