【MATLAB编程实例练习】-(38)找到将向量等分为两半的子集

该博客介绍了如何使用MATLAB解决Cody问题660,即寻找能将向量等分为两半的子集。通过示例解释了当输入向量x为[1 2 3 4 5 6 7]时,如何找到子集[1 6 7],使得其元素之和等于向量总和的一半。文章包含实现代码和优秀代码参考。
摘要由CSDN通过智能技术生成

题目

来源于Mathwork上的Cody,Problem 660 - Find a subset that divides the vector into equal halves.

Given a vector x, return the indices to elements that will sum to exactly half of the sum of all elements.
Example:
Input x = [1 2 3 4 5 6 7]
Output xi = [1 6 7]
because
sum(x) = 28
sum(x([1 6 7])) = 14
The answer is not necessarily unique and the order is unimportant. We will just test to make sure that sum(x)/2 is sum(x(xi))

代码

function xi = split_it(x)
  xi = [];
  v=1:length(x);
  x_ban=sum(x)/2;
  for i=1:length(x)
      
      C = nchoosek(v,i);
      for j=1:size(C,1)
          if sum(x(C(j,:)))==x_ban
              xi = [xi;C(j,:)];
              break;
          end
          
      end
      
      if ~isempty(xi)
          break;
      end
          
  end

end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值