在MATLAB中找到总计为特定数字的向量元素 [英] Find vector elements that sum up to specific number in MATLAB

查看:252
本文介绍了在MATLAB中找到总计为特定数字的向量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑我们有一个向量VEC.

Let us consider that we have a vector VEC.

是找到可以归纳哪些向量元素的一种方法,例如 它们在MATLAB中总计为给定的数字NUM?

Is ther a way to find which vector elements can be grouped so as they sum up to a given number NUM in MATLAB?

例如,如果VEC = [2 5 7 10]NUM = 17

所请求的算法应提供子向量[2 5 10][7 10]总计为给定NUM的答案.

The requested algorithm should provide the answer that subvectors [2 5 10] and [7 10] sum up to given NUM.

推荐答案

这是没有任何工具箱或第三方功能的另一种方法.它逐步检查VEC中所有可能的值组合,并测试总和是否等于NUM.

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

这类似于 natan的答案,但未使用conbntns.

这篇关于在MATLAB中找到总计为特定数字的向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆