Find vector elements that sum up to specific number in MATLAB

后端 未结 3 1732
温柔的废话
温柔的废话 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:38

    If I'm not mistaken this problem is NP-hard.
    But an interesting approach might be using bintprog:

    n = numel( VEC );
    x0 = zeros( 1, n ); % one possible init guess
    x = bintprog( zeros( n, 1 ), ...  % objective function meaningless, we look for feasibility
                  [], [], ... % no inequality constraints
                  VEC(:)', NUM, ... %' we want the sum of selected elements to equal NUM
                  x0 ); % changing init x0 might result with different solutions
    find( x ) 
    

    the binary vector x (the solution of the optimization in bintprog) selects the relevant elements that sum to NUM

提交回复
热议问题