Search code examples
matlabsortingfor-loop

How to find the maximum value of the sum of consecutive values in matlab


I have a data matrix containing 12 rows and 50 columns. For example, Here is the data of first column (z), values of first and second rows are negative, the next 4 numbers are positive, next one is negative, next 2 ones are positive and the last 3 numbers are negative. For example, I want to calculate the sum of first and second rows (consecutive negative numbers), then the seventh rows and then the sum of 10th, 11th and 12th rows (the consecutive negative numbers) and finally take the maximum value among 3 as output.

z= (-1.24;-2.36;1.24;2.14;3.14;1.08;-1.12;3.56;4.89;-1.12;-2.74;-3.45)


M = (-3.6; -1.12;-7.31)

result = max(M)
-7.31

Solution

  • As you show in the your example you actually want the minimum of the sum, not the maximum (-7.31 minimum, -1.12 maximum). Anyways, this could should do the trick:

    z =[-1.24;-2.36;1.24;2.14;3.14;1.08;-1.12;3.56;4.89;-1.12;-2.74;-3.45]';
    zNgv = z < 0;
    h = cumsum(diff([0;zNgv(:)]) == 1).*zNgv(:);
    S = accumarray(h + 1,z);
    nSum = nan(numel(S)*2-1,1);
    nSum(1:2:end) = S;
    
    maxS=min(nSum(2:end));
    

    To adapt it to a matrix just cycle through the columns (note that z is transposed in my code)