wewa
wewa

Reputation: 1678

Mean of two values having the same timestamp in an array

Following my question Merge 2 vectors according their time values: If two values in an array have the same timestamp I need to combine them and use the average value. How can I realize this in an elegant way?

Here is an example:

%1st column = time; 2nd column = value
%there are two values with timestamp '6'
C = [1,34;2,34;5,68;6,2;6,3;7,45]
C =

     1    34
     2    34
     5    68
     6     2
     6     3
     7    45
%after processing
C_proc =

    1.0000   34.0000
    2.0000   34.0000
    5.0000   68.0000
    6.0000    2.5000
    7.0000   45.0000

Upvotes: 1

Views: 79

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

That's what accumarray is for:

out = accumarray(C(:,1),C(:,2),[],@mean)  %// use with care, see below

If you don't want the zeros for the skipped indices, combine it with unique, which also avoids the necessary assumption of integer timestamps of the first approach:

[a,~,u] = unique(C(:,1))
out = [a accumarray(u,C(:,2),[],@mean)]

out =

    1.0000   34.0000
    2.0000   34.0000
    5.0000   68.0000
    6.0000    2.5000
    7.0000   45.0000

Upvotes: 2

Related Questions