1
votes

I have two matrix with more than 1000 rows, and two columns. Everytime the first column is '0', the second has a value, and everytime the first column is '1', the second is zero. Example:

M = [0 23;0 35;1 0;1 0;0 2;1 0]

M =

     0    23
     0    35
     1     0
     1     0
     0     2
     1     0

Let's think about the second column as a non periodic cycle.

What I want is, everytime the first column is 0 (until is one again), having the opportunity to analyse the size and sum of the second column. In the end I want to know which cycle is bigger in size and sum. (in the example matrix, as output, I know the first cycle is the bigger with a sum of 58).

1

1 Answers

4
votes

Assuming A as the input two-column array, here's one approach with accumarray -

%// Create ID array for using with accumarray
id = cumsum([1;diff(A(:,1))~=0]);

%// Get summations and counts for all IDs
sums = accumarray(id,A(:,2));
counts = accumarray(id,1);

%// Get offset in case the starting element in first column is not 0
offset = (A(1,1)~=0)+1;

%// Consider only even IDs corresponding to 0 elements cycle
sums = sums(offset:2:end)
counts = counts(offset:2:end)

Sample run -

A =
     1    34
     1    45
     0    23
     0    35
     1     0
     1     0
     0     2
     0     8
     0     6
     1     9
sums =
    58
    16
counts =
     2
     3