Find vector elements that sum up to specific number in MATLAB

后端 未结 3 1842
温柔的废话
温柔的废话 2021-01-22 05:51

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?

3条回答
  •  青春惊慌失措
    2021-01-22 06:36

    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.

提交回复
热议问题