Clear Filters
Clear Filters

I have an array of n elements like [1 2 4 8 16]. I want calculate frequency of all combinations. 1, 2 ,4 ,8, 16, 1+2, 1+4, 1+8, 1+16, 2+4, 2+8, 2+16, 4+8, 4+16, 8+16, 1+2+4, 1+2+8, 1+2+16, 1+2+4+8, 1+2+4+16, 1+2+4+8+16 How can i store output in array

2 views (last 30 days)
1, 2 ,4 ,8 ,16
1+2, 1+4, 1+8, 1+16,
2+4, 2+8, 2+16,
4+8, 4+16,
8+16,
1+2+4, 1+2+8, 1+2+16,
1+2+4+8, 1+2+4+16,
1+2+4+8+16

Accepted Answer

Matt J
Matt J on 25 Jan 2019
Edited: Matt J on 25 Jan 2019
n=numel(yourVector);
mask=dec2bin(0:2^n-1,n)-'0';
mask(1,:)=[];
combs= mask*yourVector(:) ;
result = histcounts( combs , 1:max(combs)+1);
  4 Comments
Stephen23
Stephen23 on 26 Jan 2019
Edited: Stephen23 on 26 Jan 2019
@tushar bhonsle: if you are using a MATLAB version prior to R2014b, then you will not have histcounts and will need to use histc instead, e.g.:
V = [1,2,4,8,16]
N = numel(V);
M = dec2bin(1:2^N-1)-'0';
C = M*V(:)
Z = histc(C, 1:max(C)+1)
@Matt J: surely it is easier to start from 1 than to delete the first row?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!