1

I have a MATLAB double array that looks like this:

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

It goes on for many years and many quarters, and the number of rows in each quarter and year varies unpredictably. I want to calculate the mean on Var1 for 2000 Q1, then the mean on Var1 for 2000 Q2, and so on.

I realise I could easily do this using a loop, but suspect this is not the most elegant or efficient way to program.

1 Answers1

2

Yes, there is: 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

This gives

result_mean =
    35
    43
result =
        2000           1          35
        2000           2          43
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147