Jahnny T
Jahnny T

Reputation: 47

Cumulative summation of value in each row

I have something like the following:

a = [1 11; 2 16; 3 9; 4 13; 5 8; 6 14];
b = a;
n = length(a);
Sum = [];

for i=1:1:n,
   Sum = b(i,2)+b(i+1:1:n,2)

end

b =

 1    11
 2    16
 3     9
 4    13
 5     8
 6    14

For the first iteration I am looking to find the first combination of values in the second column which are between 19 and 25.

Sum =

27
20
24
19
25

Since 20 is that first combination (Rows 1&3) -- I would like to remove that data at start a new matrix or signify that is the first combination (i.e. place a 1 next to in by creating a third column)

The next step would be to sum the values which are still in the matrix with row 2 value:

Sum =
29
24
30

Then 2&5 would be combined.

However, I would like to allow not only pairs to be combined but also several rows if possible.

Is there something I am overlooking that may simplify this problem?

Upvotes: 2

Views: 157

Answers (1)

Zac Thompson
Zac Thompson

Reputation: 12665

I don't think you're going to simplify this very much. It's a variation on the knapsack problem, which is NP-hard. The best algorithm to use might depend on the size of your inputs.

Upvotes: 1

Related Questions