Wednesday, 15 May 2013

combinatorics - Find vector elements that sum up to specific number in MATLAB -



combinatorics - Find vector elements that sum up to specific number in MATLAB -

let consider have vector vec.

is ther way find vector elements can grouped sum given number num in matlab?

for illustration if vec = [2 5 7 10] , num = 17

the requested algorithm should provide reply subvectors [2 5 10] , [7 10] sum given num.

here way solve using conbntns, function mapping toolbox retrieves possible combinations of set of values (if don't have toolbox, can utilize combinator fex). so, vector a, example, we'll find possible combination of given length (1 length of a) sum them , see equal num=17:

num=17; a=[2 5 7 10]; ii=1:numel(a) b=combntns(a,ii); c=sum(b,2); d=find(c==num); if ~isempty(d) b(d,:) end end ans = 7 10 ans = 2 5 10

of course of study can store b(d,:) output cell array or whatever future use...

matlab combinatorics

No comments:

Post a Comment