Find vector elements that sum up to specific number in MATLAB

后端 未结 3 1725
温柔的废话
温柔的废话 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 is a way to solve this using conbntns, a function from the Mapping Toolbox that retrieves all possible combinations of set of values (if you don't have this toolbox, you can use combinator from the FEX). So, for vector A, for example, we'll find all possible combination of a given length (1 to the length of A) then sum them and see which is equal to NUM=17:

    NUM=17;
    A=[2 5 7 10];
    for 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 you can store B(D,:) output into a cell array or whatever for future use...

提交回复
热议问题