基于第一列元素 - MATLAB对第二列元素求和

时间:2015-12-17 17:56:38

标签: matlab matrix

我有两个超过1000行的矩阵和两列。 每当第一列是' 0'时,第二列都有一个值,每当第一列是' 1'时,第二列是零。 例如:

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

让我们将第二列视为非周期性循环。

我想要的是,每当第一列为0时(直到再次为一列),有机会分析第二列的大小和总和。最后,我想知道哪个周期的大小和总和更大。 (在示例矩阵中,作为输出,我知道第一个周期越大,总和为58)。

1 个答案:

答案 0 :(得分:4)

假设A为输入的双列数组,这是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)

示例运行 -

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
相关问题