Matlab:对具有限制的列元素求和 [英] Matlab: sum column elements with restrictions

查看:260
本文介绍了Matlab:对具有限制的列元素求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个MxN矩阵和一个约束cstrn = 100;.

We have a MxN matrix and a constrain cstrn = 100;.

约束是列元素的汇总限制(每列):

The constrain is the summarize limit of column's elements (per column):

sum(matrix(:,:))<=cstrn.

对于给定的示例如下:

Columns 1 to 5:
  15  18  -5 22 19
  50  98 -15 39 -8
  70 -15  80 45 38
  31  52   9 80 72
  -2  63  52 71  6
   7  99  32 58 41 

我想找到满足此约束的每列最大元素数.

I want to find the max number of element per column who fulfill this constrain.

我如何总结每个列元素以及同一列中的其他元素,并找出哪种总和组合使用每列的最大元素数?

How can i summarize every column element with the others elements in same column and find which sum combinations uses the max number of elements per column?

在给定的示例中,解决方案是:

In the given example solution is:

   4  3  5  2  5

其中

column 1: 15 + 50 + 31 +7 +(-2)

column 2: 18 +(-15) + 52 or 63

谢谢.

推荐答案

由于将小元素适合总和总是比较容易的,因此您可以执行sort,然后进行累积总和:

Since it is always easier to fit small elements into a sum, you can do a sort, followed by the cumulative sum:

m= [
  15  18  -5 22 19
  50  98 -15 39 -8
  70 -15  80 45 38
  31  52   9 80 72
  -2  63  52 71  6
   7  99  32 58 41]; 

cs = cumsum(sort(m))
cs =
    -2   -15   -15    22    -8
     5     3   -20    61    -2
    20    55   -11   106    17
    51   118    21   164    55
   101   216    73   235    96
   171   315   153   315   168

现在,您可以轻松确定超出阈值cnstrn的位置(感谢@sevenless)!

Now you easily identify at which element you cross the threshold cnstrn (thanks, @sevenless)!

out = sum(cs <= cnstrn)

out =
     4     3     5     2     5

这篇关于Matlab:对具有限制的列元素求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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