根据数组中的其他值计算 MATLAB 数组中均值的最佳方法?

Best way to calculate means within a MATLAB array based on other values in the array?

我有一个如下所示的 MATLAB 双精度数组:

YEAR    QUARTER ID  VAR1    VAR2
2000    1       1   50      20
2000    1       2   20      34
2000    2       1   43      33

它持续了很多年和很多个季度,每个季度和每年的行数变化莫测。我想计算 2000 年第一季度 Var1 的平均值,然后计算 2000 年第二季度 Var1 的平均值,依此类推。

我知道我可以使用循环轻松地做到这一点,但怀疑这不是最优雅或最有效的编程方式。

是的,有:accumarray:

data = [ 2000    1       1   50      20
         2000    1       2   20      34
         2000    2       1   43      33]; %// example data
[u, ~, v] = unique(data(:, [1 2]), 'rows'); %// get groups (u) and integer labels (v)
result_mean = accumarray(v, data(:,4), [], @mean); %// mean within each group
result = [u result_mean]; %// built result in matrix form

这给出了

result_mean =
    35
    43
result =
        2000           1          35
        2000           2          43