Let us consider that we have a vector VEC.
Is ther a way to find which vector elements can be grouped so as they sum up to a given number NUM in MATLAB?
Here's another way to do it without any toolboxes or third party functions. It steps through all possible combinations of values in VEC and tests if the sum equals NUM.
VEC = [2 5 7 10]
NUM = 17;
n = length(VEC);
for i = 1:(2^n - 1)
ndx = dec2bin(i,n) == '1';
if sum(VEC(ndx)) == NUM
VEC(ndx)
end
end
ans =
7 10
ans =
2 5 10
This is similar to natan's answer, but without using conbntns.